C# Lock and Async Method

后端 未结 4 1828
星月不相逢
星月不相逢 2021-02-05 03:22

I am not clear (and can\'t find documentation clear enough): when using the lock keyword in an async method: will the thread be blocked if the object is already blocked or will

4条回答
  •  时光取名叫无心
    2021-02-05 03:56

    This has been disallowed to stop deadlocks (i.e. developers hurting themselves). The best solution I've found is to use semaphores - See this post for details.

    Relevant code extract:

    static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);
    
    ...
    
    await semaphoreSlim.WaitAsync();
    try
    {
        await Task.Delay(1000);
    }
    finally
    {
        semaphoreSlim.Release();
    }
    

提交回复
热议问题