Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

c# - Difference between Task.Run and QueueBackgroundWorkItem in Asp.Net

What exactly is the difference using

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

or

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

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.

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.

So what is special about QueueBackgroundWorkItem then?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation has an excellent explanation:

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...