异步方法中的信号量等待与WaitAsync [英] Semaphore Wait vs WaitAsync in an async method

查看:360
本文介绍了异步方法中的信号量等待与WaitAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在这种情况下使用的Wait和WaitAsync的SemaphoreSlim使用之间的区别:

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;
}


推荐答案

如果您有异步方法-您希望尽可能避免任何阻塞呼叫。 SemaphoreSlim.Wait()是阻止调用。那么,如果您使用 Wait()且当前无法使用信号量,将会发生什么?它将阻止调用方,这对于异步方法是非常出乎意料的:

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

如果您使用 WaitAsync

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

当心将常规锁定机制与async\await一起使用。执行完此操作之后:

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

result = await this.GetStringAsync();

在等待 之后,您可能正在其他线程上,这意味着当您尝试释放获取的锁时,它可能会失败,因为您尝试释放的锁不是从获取该锁的同一线程释放的。请注意,信号量是的情况,因为它不具有线程亲缘关系(与其他类似 Monitor.Enter ReaderWriterLock 等)。

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).

这篇关于异步方法中的信号量等待与WaitAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆