5

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?

nimbudew
  • 958
  • 11
  • 28
  • 1
    If you are guarding resources in the same process then [Luaan's answer](http://stackoverflow.com/a/31716939/2681948) should do the job. In case you need to guard resources between processes (the main role of mutex as I think) then take a look at [this question](http://stackoverflow.com/q/23153155/2681948). – Romasz Jul 30 '15 at 08:02

1 Answers1

10

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();
}
Luaan
  • 62,244
  • 7
  • 97
  • 116