Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling await operation after acquiring mutex [duplicate]

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?

like image 788
nimbudew Avatar asked Jul 30 '15 06:07

nimbudew


1 Answers

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();
}
like image 129
Luaan Avatar answered Nov 02 '22 23:11

Luaan