Semaphore Wait vs WaitAsync in an asynchronous method

I am trying to figure out what is the difference between using SemaphoreSlim Wait and WaitAsync used in this context:

private SemaphoreSlim semaphore = new SemaphoreSlim(1);
public async Task<string> Get()
{
   // What 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;
}
+4
source share
2 answers

If you have an asynchronization method, you want, if possible, to avoid any blocking calls. SemaphoreSlim.Wait()- blocking call. So what happens if you use Wait()and the semaphore is not available at the moment? It will block the caller, which is very unexpected for asynchronous 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 the semaphore is not available at the moment.

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

async\await. :

result = await this.GetStringAsync();

await, , , , , , . , , ( , Monitor.Enter, ReaderWriterLock ..).

+7

, Wait , WaitAsync - .

+3

Source: https://habr.com/ru/post/1678329/


All Articles