Calling await operation after acquiring mutex

Fli*_*per 5 c# mutex windows-phone-8.1

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();
}
Run Code Online (Sandbox Code Playgroud)

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?

Lua*_*aan 8

This is a job for a monitor (or to make this more async-friendly, a semaphore), not a mutex.

问题是继续 toWriteTextAsync很可能在单独的线程上运行,因此它无法释放互斥锁 - 这只能从最初获取互斥锁的同一线程中完成。

var semaphore = new SemaphoreSlim(1);

await semaphore.WaitAsync();

try
{
    await FileIO.WriteTextAsync(filename, text);
    Debug.WriteLine("written");
}
finally
{
    semaphore.Release();
}
Run Code Online (Sandbox Code Playgroud)