Vitalii

Untitled

May 11th, 2014
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. public static async Task<T> ReadJsonExSafe<T>(String fileName)
  2.         {
  3.             if (String.IsNullOrEmpty(fileName)) return default(T);
  4.  
  5.             string mutexName = "dependantOnApp" + fileName;
  6.             return await TaskEx.Run(() =>
  7.             {
  8.                 using (var myMutex = new Mutex(false, mutexName))
  9.                 {
  10.                     try
  11.                     {
  12.                         myMutex.WaitOne();
  13.                         using (var store = IsolatedStorageFile.GetUserStoreForApplication())
  14.                         using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Open, store))
  15.                         using (var sr = new StreamReader(stream))
  16.                         using (var jr = new JsonTextReader(sr))
  17.                             return (T)jsonSerializer.Deserialize(jr);
  18.                     }
  19.                     catch { throw new Exception("Exception"); }
  20.                     finally { myMutex.ReleaseMutex(); }
  21.                 }
  22.             });
  23.         }
  24.  
  25.         public static async Task<bool> WriteJsonExSafe<T>(String fileName, T content)
  26.         {
  27.             if (String.IsNullOrEmpty(fileName))
  28.                 return false;
  29.  
  30.             string mutexName = "dependantOnApp" + fileName;
  31.  
  32.             return await TaskEx.Run(() =>
  33.             {
  34.                 using (var myMutex = new Mutex(false, mutexName))
  35.                 {
  36.                     try
  37.                     {
  38.                         myMutex.WaitOne();
  39.                         using (var store = IsolatedStorageFile.GetUserStoreForApplication())
  40.                         {
  41.                             store.CreateFolderIfNecessary(fileName);
  42.                             using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, store))
  43.                             using (var sw = new StreamWriter(stream))
  44.                             using (var jw = new JsonTextWriter(sw))
  45.                                 jsonSerializer.Serialize(jw, content);
  46.                         }
  47.                     }
  48.                     catch { throw new Exception("Exception"); }
  49.                     finally { myMutex.ReleaseMutex(); }
  50.  
  51.                     return true;
  52.                 }
  53.             });
  54.         }
Advertisement
Add Comment
Please, Sign In to add comment