Last active
January 1, 2016 04:19
-
-
Save tanaka-takayoshi/8091115 to your computer and use it in GitHub Desktop.
Windows Phoneのアプリとバックグラウンドタスクでデータを共有するためのクラス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.IO.IsolatedStorage; | |
using System.Linq; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Xml.Serialization; | |
namespace Chatwork.Service.Shared | |
{ | |
public class MyStatus | |
{ | |
public string Token { get; set; } | |
public int Unread { get; set; } | |
public int Mention { get; set; } | |
public int MyTask { get; set; } | |
} | |
public static class MutexedIsoStorageFile | |
{ | |
private const String IsoStorageDateFile = "Chatwork.Service.WP.My.xml"; | |
public static MyStatus Read() | |
{ | |
var mutex = new Mutex(false, "Chatwork.Service.WP"); | |
mutex.WaitOne(); | |
try | |
{ | |
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) | |
using (var stream = new IsolatedStorageFileStream(IsoStorageDateFile, FileMode.OpenOrCreate, FileAccess.Read, store)) | |
using (var reader = new StreamReader(stream)) | |
{ | |
var serializer = new XmlSerializer(typeof(MyStatus)); | |
var status = (MyStatus)serializer.Deserialize(reader); | |
return status; | |
} | |
} | |
finally | |
{ | |
mutex.ReleaseMutex(); | |
} | |
} | |
public static void Write(MyStatus data) | |
{ | |
var mutex = new Mutex(false, "Chatwork.Service.WP"); | |
mutex.WaitOne(); | |
try | |
{ | |
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) | |
using (var stream = new IsolatedStorageFileStream(IsoStorageDateFile, | |
FileMode.Create, | |
FileAccess.Write, | |
store)) | |
{ | |
var serializer = new XmlSerializer(typeof(MyStatus)); | |
serializer.Serialize(stream, data); | |
} | |
} | |
finally | |
{ | |
mutex.ReleaseMutex(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment