Asp.Net中Task.Run和QueueBackgroundWorkItem之间的区别 [英] Difference between Task.Run and QueueBackgroundWorkItem in Asp.Net

查看:404
本文介绍了Asp.Net中Task.Run和QueueBackgroundWorkItem之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用

Task.Run(() => { 
     LongRunningMethod();
});

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

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

I tested on an Asp.Net MVC application in which I kept on writing a line to a text file for about 10 minutes inside an asynchronous task which is invoked using Task.Run or QBWI.

使用Task和QBWI都可以。我的异步方法持续写入该文件,直到10分钟没有任何问题。我没有观察到IIS对回收的影响。

It goes fine both using Task and QBWI. My async method keeps on writing to that file without any issues till 10 minutes. No disturbance from IIS I observed regarding its recycling.

那么QueueBackgroundWorkItem有什么特别之处?

So what is special about QueueBackgroundWorkItem then?

推荐答案

文档有一个很好的解释:


与普通ThreadPool工作项的区别在于, ASP.NET可以保留
跟踪当前正在通过此API注册的工作项有多少
正在运行,并且ASP.NET运行时将尝试延迟AppDomain关闭
,直到这些工作项执行完毕。

在ASP.NET管理的AppDomain外部调用。当应用程序关闭
时,将发出提供的
CancellationToken的信号。

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回收发生在在IIS中预设的特定时间。如果您真的想测试发生了什么,可以尝试强制回收

Task.Factory.StartNew does not register work with the ASP.NET runtime at all. You're running your code for 10 minutes, that makes no difference. IIS recycle happens at particular times which are preset in IIS. If you really want to test whats going on, you can attempt to force a recycle.

这篇关于Asp.Net中Task.Run和QueueBackgroundWorkItem之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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