Need to understand the usage of SemaphoreSlim

后端 未结 3 1413
走了就别回头了
走了就别回头了 2020-12-23 02:53

Here is the code I have but I don\'t understand what SemaphoreSlim is doing.

async Task WorkerMainAsync()
{
    SemaphoreSlim ss = new Semaphore         


        
3条回答
  •  [愿得一人]
    2020-12-23 03:18

    Although I accept this question really relates to a countdown lock scenario, I thought it worth sharing this link I discovered for those wishing to use a SemaphoreSlim as a simple asynchronous lock. It allows you to use the using statement which could make coding neater and safer.

    http://www.tomdupont.net/2016/03/how-to-release-semaphore-with-using.html

    I did swap _isDisposed=true and _semaphore.Release() around in its Dispose though in case it somehow got called multiple times.

    Also it is important to note SemaphoreSlim is not a reentrant lock, meaning if the same thread calls WaitAsync multiple times the count the semaphore has is decremented every time. In short SemaphoreSlim is not Thread aware.

    Regarding the questions code-quality it is better to put the Release within the finally of a try-finally to ensure it always gets released.

提交回复
热议问题