命名的mutex与AWAIT [英] Named Mutex with await

查看:127
本文介绍了命名的mutex与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:


  1. 请不要使用在等待期间,你持有的互斥的临界区

  2. 调用互斥呼叫的TaskScheduler 仅具有一个单独的线程

  1. Do not use await in the critical section during which you hold the mutex
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆