Skip to content

Instantly share code, notes, and snippets.

@tanaka-takayoshi
Last active January 1, 2016 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaka-takayoshi/8091115 to your computer and use it in GitHub Desktop.
Save tanaka-takayoshi/8091115 to your computer and use it in GitHub Desktop.
Windows Phoneのアプリとバックグラウンドタスクでデータを共有するためのクラス
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