我试图找出在这种情况下使用的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
发布评论