Locking with nested async calls

前端 未结 4 1504
轮回少年
轮回少年 2021-02-13 11:50

I am working on a multi threaded WindowsPhone8 app that has critical sections within async methods.

Does anyone know of a way to properly use semaphores / mutexes in C

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 12:46

    First, read through Stephen Cleary's blog post, which he linked to in his answer. He mentions multiple reasons, such as uncertain lock state and inconsistent invariants, which are associated with recursive locks (not to mention recursive async locks). If you can do the refactoring he and Knickedi describe in their answers, that would be great.

    However, there are some cases where that type of refactoring is just not possible. Fortunately, there are now multiple libraries which support nested async calls (lock reentrance). Here are two. The author of the first has a blog post where he talks more about it.

    • https://github.com/neosmart/AsyncLock
    • https://github.com/mysteryjeans/Flettu/

    You can incorporate it into your code as such (using the first library in this example):

    public class Foo
    {
        AsyncLock _lock = new AsyncLock();
    
        public async Task Bar()
        {
               // This first LockAsync() call should not block
               using (await _lock.LockAsync())
               {
                   await BarInternal();
               }
         }
    
        public async Task BarInternal()
        {
               // This second call to LockAsync() will be recognized
               // as being a reëntrant call and go through
               using (await _lock.LockAsync()) // no deadlock
               {
                   // do work
               }
         }
    }
    

提交回复
热议问题