I am trying to protect my isolated storage using a mutex in order to access it both from a mobile application and from BackgroundAudioPlayer.
This is my class of helpers for accessing files in isostorage:
public static async Task WriteToFile(string text)
{
using (var mut = new Mutex(false, "IsoStorageMutex"))
{
mut.WaitOne();
try
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(text.ToCharArray());
var local = ApplicationData.Current.LocalFolder;
var dataFolder = await local.CreateFolderAsync("MusicFolder",
CreationCollisionOption.OpenIfExists);
var file = await dataFolder.CreateFileAsync("Streams.txt",
CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
finally
{
mut.ReleaseMutex();
}
}
}
public static async Task<string> ReadFile()
{
using (var mut = new Mutex(false, "IsoStorageMutex"))
{
mut.WaitOne();
var result = String.Empty;
try
{
var local = ApplicationData.Current.LocalFolder;
if (local != null)
{
var dataFolder = await local.GetFolderAsync("MusicFolder");
var file = await dataFolder.OpenStreamForReadAsync("Streams.txt");
using (var streamReader = new StreamReader(file))
{
result = streamReader.ReadToEnd();
}
}
}
finally
{
mut.ReleaseMutex();
}
return result;
}
}
But when I try to access it in the background agent, I get this error:
Object synchronization method was called from an unsynchronized block of code.
Stacktrace:
at System.Threading.Mutex.ReleaseMutex()
at YouRadio.IsolatedStorage.StorageHelpers.<ReadFile>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at YouRadio.AudioPlaybackAgent.AudioPlayer.<AddTracksFromIsoStorageToPlaylist>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at YouRadio.AudioPlaybackAgent.AudioPlayer.<OnUserAction>d__2.MoveNext()
What am I doing wrong?
source
share