命名的mutex与AWAIT [英] Named Mutex with await
问题描述
因此,我不能使用线程仿射锁异步
- ?我怎么能运行多个进程时,守护我的资源
Hence I can't use thread-affine locks with async
- how can I guard my resources when running multiple processes?
例如我已经使用下面的任务两个过程:
For example I've two processes that use a Task below:
public async Task<bool> MutexWithAsync()
{
using (Mutex myMutex = new Mutex(false, "My mutex Name"))
{
try
{
myMutex.WaitOne();
await DoSomething();
return true;
}
catch { return false; }
finally { myMutex.ReleaseMutex(); }
}
}
如果一个互斥锁保护的moethod然后上面code同步将工作但异步
我会得到:
If the moethod guarded by a Mutex is synchronous then above code will work but with async
I will get:
对象同步方法从code的不同步块调用。
Object synchronization method was called from an unsynchronized block of code.
所以被命名互斥没用异步code?
So is Named Mutex useless with asynchronous code?
推荐答案
您必须确保互斥正在对某个线程一致访问。你可以做,在许多方面:
You must ensure that mutex is being accessed consistently on a certain thread. You could do that in a number of ways:
- 请不要使用在等待期间,你持有的互斥的临界区
- 调用互斥呼叫
的TaskScheduler
仅具有一个单独的线程
- Do not use await in the critical section during which you hold the mutex
- Invoke the mutex calls on a
TaskScheduler
that only has a single thread
这可能看起来像这样:
await Task.Factory.StartNew(() => mutex.WaitOne(), myCustomTaskScheduler);
或者,您可以使用同步code和移动一切的线程池。如果您只能访问的DoSomething
的异步版本,只考虑调用 Task.Wait
其结果。您会在这里遭遇轻微的低效率。也许还不错。
Or, you use synchronous code and move everything to the thread-pool. If you only have access to an async version of DoSomething
, consider just calling Task.Wait
on its result. You'll suffer a minor inefficiency here. Probably fine.
这篇关于命名的mutex与AWAIT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!