Locking with nested async calls

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

    Recursive locks are a really bad idea (IMO; link is to my own blog). This is especially true for async code. It's wicked difficult to get async-compatible recursive locks working. I have a proof-of-concept here but fair warning: I do not recommend using this code in production, this code will not be rolled into AsyncEx, and it is not thoroughly tested.

    What you should do instead is restructure your code as @svick stated. Something like this:

    public async Task Bar()
    {
        await _lock.WaitAsync();
    
        await BarInternal_UnderLock();
    
        _lock.Release();
    }
    
    public async Task BarInternal()
    {
        await _lock.WaitAsync();
    
        await BarInternal_UnderLock();
    
        _lock.Release();
    }
    
    private async Task BarInternal_UnderLock()
    {
        // DO work
    }
    

提交回复
热议问题