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 = new SemaphoreSlim(1);
public async Task<string> Get()
{
// What's the difference between using Wait and WaitAsync here?
this.semaphore.Wait(); // await this.semaphore.WaitAsync()
string result;
try {
result = this.GetStringAsync();
}
finally {
this.semaphore.Release();
}
return result;
}
The difference is that
Wait
blocks the current thread until semaphore is released, whileWaitAsync
does not.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 useWait()
and semaphore is not available at the moment? It will block the caller, which is very unexpected thing for async methods:If you use
WaitAsync
- it will not block the caller if semaphore is not available at the moment.Also you should beware to use regular locking mechanisms together with async\await. After doing this:
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 likeMonitor.Enter
,ReaderWriterLock
and so on).