异步方法中的信号量等待与WaitAsync

编程入门 行业动态 更新时间:2024-10-24 20:19:58
本文介绍了异步方法中的信号量等待与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

本文发布于:2023-10-09 06:23:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474950.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:信号量   方法   WaitAsync

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!