Task.Run 和 Asp.Net 中的 QueueBackgroundWorkItem 之间的区别

Difference between Task.Run and QueueBackgroundWorkItem in Asp.Net

使用

到底有什么区别
Task.Run(() => { 
     LongRunningMethod();
});

HostingEnvironment.QueueBackgroundWorkItem(clt => LongRunningMethod());

我在 Asp.Net MVC 应用程序上进行了测试,在该应用程序中,我在使用 Task.Run 或 QBWI 调用的异步任务中持续向文本文件写入一行约 10 分钟。

使用 Task 和 QBWI 都很好。我的异步方法一直在毫无问题地写入该文件,直到 10 分钟。我没有观察到 IIS 对它的回收造成干扰。

那么QueueBackgroundWorkItem有什么特别之处呢?

documentation有一个很好的解释:

Differs from a normal ThreadPool work item in that ASP.NET can keep track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing. This API cannot be called outside of an ASP.NET-managed AppDomain. The provided CancellationToken will be signaled when the application is shutting down.

Task.Factory.StartNew 根本不在 ASP.NET 运行时注册工作。您 运行 您的代码 10 分钟,这没有什么区别。 IIS 回收发生在 preset in IIS. If you really want to test whats going on, you can attempt to force a recycle.

的特定时间

下面的文章解释了与您正在做的类似的事情,如果您转到最后一部分 "Few more thoughts..." 您会看到两者之间突出显示的区别

http://codingcanvas.com/using-hostingenvironment-queuebackgroundworkitem-to-run-background-tasks-in-asp-net/

基本上它说使用 queuebackgroundworkitem 任务在 ASP.Net 运行时注册,如果进程关闭或崩溃 ASP.NET 运行时仍然为进程提供一些宽限期 complete.It 也涉及向进程发送通知,以便它可以结束并执行任何完成任务,而当您使用 Task.Run

时,所有这些都不可用

AppDomain关闭只能延迟90秒(实际上是HttpRuntimeSection.ShutdownTimeout和processModel shutdownTimeLimit中的最小值)。如果排队的项目太多以至于无法在 90 秒内完成,ASP.NET 运行时将卸载 AppDomain,而不等待工作项目完成。

https://blogs.msdn.microsoft.com/webdev/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-background-processes-in-asp-net/