获取互斥量后调用await操作 [英] Calling await operation after acquiring mutex
问题描述
如何在获取 mutex
后使用 await FileIO.WriteTextAsync()
(在 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();
}
但该方法仅适用于一两次迭代,之后它会抛出一个System.Exception
.此外,如果我删除 await
关键字或完全删除文件写入方法,代码运行得非常好.所以,所有的麻烦都是由调用异步方法引起的.我该怎么做才能解决这个问题?
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.
问题是 WriteTextAsync
的延续很可能在一个单独的线程上运行,所以它不能释放互斥量 - 这只能从与最初获取互斥锁的线程相同.
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();
}
这篇关于获取互斥量后调用await操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!