Locking with nested async calls

前端 未结 4 1507
轮回少年
轮回少年 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:28

    Here's what I did in such a situation (still, I'm not experienced with tasks, so don't beat me ;-)
    So basically you have move the actual implementation to non locking methods and use these in all methods which acquire a lock.

    public class Foo
    {
        SemaphoreSlim _lock = new SemaphoreSlim(1);
    
        public async Task Bar()
        {
            await _lock.WaitAsync();
            await BarNoLock();
            _lock.Release();
         }
    
        public async Task BarInternal()
        {
            await _lock.WaitAsync(); // no deadlock
            await BarNoLock();
            _lock.Release();
         }
    
         private async Task BarNoLock()
         {
             // do the work
         }
    }
    

提交回复
热议问题