是否应弃用Task.Wait? [英] Should Task.Wait be deprecated?

查看:75
本文介绍了是否应弃用Task.Wait?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解了调用Task的困难方式.从池线程中等待可能导致线程饥饿死锁.

I learnt the hard way that calling Task.Wait from a pool thread can lead to thread-starvation deadlock.

根据此MSDN文章,在死锁"一章中,我们应该遵守这两个规则:

According to this MSDN article, in chapter 'deadlocks', we should obey these two rules:

  • 请勿创建任何其同步方法等待异步功能的类,因为可以从池中的线程调用该类.
  • 如果此类阻止正在等待异步功能的类,请不要在异步功能内使用任何类.

似乎唯一可以合法使用Task的地方.等待是Main函数-我在这里有点夸张,但是您明白了.

It seems the only place left for a legitimate use of Task.Wait is the Main function - I am exaggerating a bit here but you get the idea.

为什么Task.Wait仍然是.NET框架的一部分,看到它有多危险?

Why is Task.Wait still part of the .NET framework, seeing how dangerous it is?

推荐答案

为什么Task.Wait仍然是.NET框架的一部分,了解如何 危险吗?

Why is Task.Wait still part of the .NET framework, seeing how dangerous it is?

因为您希望能够在Task上进行同步阻止.很少,但您仍然这样做.如您所说,Main可能是最流行(最好是唯一)的地方.那,以及Microsoft因其向后兼容而臭名昭著的事实,因此,一旦引入此功能,就不太可能被BCL弃用或消失. Task.WaitAll也是如此.

Because you want to be able to synchronously block on a Task. Rarely, but you still do. As you said, Main is probably the most popular (and preferably the only) place where that would happen. That, and the fact that Microsoft is notorious for it's backwards compatability, so once this was introduced, it is highly unlikely to be deprecated or disappear from the BCL. Same goes for Task.WaitAll.

真正的问题当人们没有正确阅读文档并且不理解调用这种方法的含义并最终滥用该方法时,IMO就开始了.如果您仔细使用它,它的确很棒.

The real problem IMO starts when people don't properly read the documentation and don't understand the implications of calling such a method and end up misusing it. If you use it carefully, it does it's job great.

另一件事是您不能始终完全同步 .不幸的是,很多时候您都有通过签名同步的代码,这些代码无法更改,需要调用异步方法调用.是的,这很危险,所有人都不要这样做,它被认为是 具有异步代码的反模式 ,我本人至少回答了十几个关于SO的问题,人们最终陷入僵局,不知道为什么,但是TPL作者仍然需要使这些类型的通话成为可能.

Another thing is the fact that you can't always go async all the way. Unfortunately, many times you have code, which is synchronous by signature, which can't be altered and needs to invoke an async method call. Yes, this is dangerous and discouraged by all and is considered an anti-pattern with async code, and I myself have answered at least a dozen question on SO where people end up deadlocking themselves and don't understand why, but the TPL authors still needed to make these type of calls possible.

这篇关于是否应弃用Task.Wait?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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