使用 await 命名 Mutex [英] Named Mutex with await
问题描述
因此我不能在 async
中使用线程仿射锁 - 在运行多个进程时如何保护我的资源?
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(); }
}
}
如果 Mutex 保护的方法是同步的,那么上面的代码可以工作,但是使用 async
我会得到:
If the method guarded by a Mutex is synchronous then above code will work but with async
I will get:
从未同步的代码块调用对象同步方法.
Object synchronization method was called from an unsynchronized block of code.
那么 Named Mutex 对异步代码没用吗?
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:
- 不要在持有互斥锁的临界区使用 await
- 在只有一个线程的
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);
或者,您使用同步代码并将所有内容移至线程池.如果您只能访问 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.
这篇关于使用 await 命名 Mutex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!