Semaphore Wait vs WaitAsync in an async method

前端 未结 2 1363
情话喂你
情话喂你 2021-02-07 15:52

I\'m trying to find out what is the difference between the SemaphoreSlim use of Wait and WaitAsync, used in this kind of context:

private SemaphoreSlim semaphore         


        
相关标签:
2条回答
  • 2021-02-07 16:10

    The difference is that Wait blocks the current thread until semaphore is released, while WaitAsync does not.

    0 讨论(0)
  • 2021-02-07 16:31

    If you have async method - you want to avoid any blocking calls if possible. SemaphoreSlim.Wait() is a blocking call. So what will happen if you use Wait() and semaphore is not available at the moment? It will block the caller, which is very unexpected thing for async methods:

    // this will _block_ despite calling async method and using await
    // until semaphore is available
    var myTask = Get();
    var myString = await Get(); // will block also
    

    If you use WaitAsync - it will not block the caller if semaphore is not available at the moment.

    var myTask = Get();
    // can continue with other things, even if semaphore is not available
    

    Also you should beware to use regular locking mechanisms together with async\await. After doing this:

    result = await this.GetStringAsync();
    

    You may be on another thread after await, which means when you try to release the lock you acquired - it might fail, because you are trying to release it not from the same thread you acquired it. Note this is NOT the case for semaphore, because it does not have thread affinity (unlike other such constructs like Monitor.Enter, ReaderWriterLock and so on).

    0 讨论(0)
提交回复
热议问题