首页 新闻 会员 周边

.NET Core 中 ManualResetEventSlim 会阻塞当前线程吗

2
悬赏园豆:200 [已解决问题] 解决于 2019-04-30 10:26

比如下面的代码,在 mres.Set() 没有被调用的时候,当前线程是不是会被一直阻塞(blocking)着?

var args = new SocketAsyncEventArgs();
using (var mres = new ManualResetEventSlim())
{
    args.Completed += (s, e) => mres.Set();
    if (socket.ConnectAsync(args))
    {
        if (!mres.Wait(timeout))
        {
            throw new TimeoutException("Could not connect to " + endpoint);
        }
    }
}

如果会阻塞当前线程, mres.Wait 返回 false 时是不是会释放当前线程?
如果会阻塞当前线程,在 async 方法中使用会带来什么后果?

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2019-04-29 20:09
< >
分享
最佳答案
1
  1. mres.Set 被调用之前,执行这段代码的线程会被阻塞
  2. Talk is cheap, Try it online!
  3. 后果就是会阻塞住执行 Task 的线程,例子中的 socket.ConnectAsyncIO Pending, 这意味着 There is no thread, 与其花时间在这里等着,不如让当前的线程去干点别的
收获园豆:200
不如隐茶去 | 小虾三级 |园豆:559 | 2019-04-29 21:47

Using Async with ManualResetEventSlim 也提到了

Using WatiHandle.WaitOne, or similar waits on a thread pool thread causes that thread to be busy waiting and thus consuming one ThreadPool Thread as seen in the debugger.

dudu | 园豆:30994 (高人七级) | 2019-04-30 10:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册