Task.Run与ThreadPool.QueueUserWorkItem [英] Task.Run vs ThreadPool.QueueUserWorkItem

查看:496
本文介绍了Task.Run与ThreadPool.QueueUserWorkItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是主题专家,我试图了解.NET中可用的更多异步世界. Task.Run和ThreadPool.QueueUserWorkItem都允许在池线程上分派工作,但是两者之间有什么区别,或者,如果您愿意,两者之间有什么优缺点? 以下是我的优点列表.不知道它是完整的还是正确的.

Not a subject expert I'm trying to understand more of the async world available in .NET. Task.Run and ThreadPool.QueueUserWorkItem both allow dispatching work on a pool thread but what are the differences or, if you prefer, pros and cons of the two? Following is my list of pros. Not sure if it is complete or even correct.

ThreadPool.QueueUserWorkItem优点:

ThreadPool.QueueUserWorkItem pros:

  • 传递论点的可能性

Task.Run专业人士:

Task.Run pros:

  • 提供CancellationToken的可能性
  • 等待任务完成的可能性
  • 向调用代码返回值的可能性

推荐答案

ThreadPool.QueueUserWorkItem只是做与Task.Run(在.NET 4.5中引入)相同的工作的较早实现(在.NET 1.1中引入).

ThreadPool.QueueUserWorkItem is just the older implementation (introduced in .NET 1.1) of doing the same job as Task.Run (introduced in .NET 4.5).

Microsoft尝试避免破坏.NET中的向后兼容性. 为.NET 1.1编写的内容可以(通常)无需更改就可以在.NET 4.5中进行编译和运行. 重大更改通常来自编译器更改,而不是框架更改,例如在lambada中使用的foreach中声明的变量在C#5和更高版本中的行为有所不同.

Microsoft tries to avoid breaking backwards compatibility in .NET. Something written for .NET 1.1 can be compiled and ran in .NET 4.5 with (usually) no changes. Breaking changes are usually from compiler changes, not framework changes, like the variable declared in a foreach used inside a lambada behaving differently in C# 5 and newer.

当您拥有Task.Run时,没有真正的理由使用ThreadPool.QueueUserWorkItem.

There is no real reason to use ThreadPool.QueueUserWorkItem when you have Task.Run.

一个终点:具有讽刺意味的是, HostingEnvironment.QueueBackgroundWorkItem(...) . 它使您可以在ASP.NET环境中的后台线程上运行某些内容,并通过Web服务器通知AppDomain关闭(在长时间的不活动状态下经常发生)来通知后台工作.

One ending point: ironically, things have actually come full circle with HostingEnvironment.QueueBackgroundWorkItem(...). It lets you run something on a background thread in a ASP.NET environment and let the background work be notified of AppDomain shutdowns by the web server (which can frequently happen during long periods of inactivity).

这篇关于Task.Run与ThreadPool.QueueUserWorkItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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