How can I write to a file using await FileIO.WriteTextAsync()
(in Windows Phone 8.1) after acquiring mutex
so that no two threads access the same file and mutual exclusion is ensured. I'm doing the following:
mutex.WaitOne()
try
{
await FileIO.WriteTextAsync(filename, text);
Debug.WriteLine("written");
}
finally
{
mutex.ReleaseMutex();
}
But the method works for one or two iterations only, after which it throws a System.Exception
. Also, if I remove the await
keyword or remove the file writing method entirely, the code runs perfectly fine. So, all trouble is caused by calling an async method. What can I do to resolve this?
This is a job for a monitor (or to make this more async-friendly, a semaphore), not a mutex.
The problem is that the continuation to WriteTextAsync
is likely to run on a separate thread, so it can't release the mutex - that can only be done from the same thread that originally acquired the mutex.
var semaphore = new SemaphoreSlim(1);
await semaphore.WaitAsync();
try
{
await FileIO.WriteTextAsync(filename, text);
Debug.WriteLine("written");
}
finally
{
semaphore.Release();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With