Named Mutex with await

后端 未结 5 2141
感动是毒
感动是毒 2020-11-30 09:56

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 u

5条回答
  •  情书的邮戳
    2020-11-30 10:53

    You can use a binary Semaphore instead of a Mutex. A Semaphore does not need to be release by the same thread that acquired it. The big disadvantage here is if the application crashes or is killed within DoSomething() the semaphore will not be released and the next instance of the app will hang. See Abandoned named semaphore not released

     public async Task MutexWithAsync()
     {
         using (Semaphore semaphore = new Semaphore(1, 1, "My semaphore Name"))
         {
             try
             {
                 semaphore.WaitOne();
                 await DoSomething();
                 return true;
             }
             catch { return false; }
             finally { semaphore.Release(); }
         }
     }
    

提交回复
热议问题