[英]Using Task within QueueBackgroundWorkItem
I was diving into the QueueBackgroundWorkItem
class recently, and I've stumbled across samples I do not understand.我最近正在深入研究
QueueBackgroundWorkItem
类,并且偶然发现了一些我不理解的示例。
My understanding is that QueueBackgroundWorkItem
creates a new thread, in which the given Action
or Func
is executed, and there is no need to manually create a new Thread or Task.我的理解是
QueueBackgroundWorkItem
新建一个线程,在其中执行给定的Action
或者Func
,不需要手动新建一个Thread或者Task。
However, many samples I see create a new Task within the Action executed, like this one (copied from here ):但是,我看到的许多示例在执行的 Action 中创建了一个新任务,如下所示(从此处复制):
using System.Web.Mvc;
using System.Web.Hosting;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System;
namespace MyApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
//Sample 1
//Action overload
//with lambda expression
HostingEnvironment.QueueBackgroundWorkItem(
clt => LongRunningAction(clt)
);
//Sample 2
//Action overload
//without lambda expression
HostingEnvironment.QueueBackgroundWorkItem(
(Action)LongRunningAction
);
//Sample 3
//Action overload
//with lambda expression
HostingEnvironment.QueueBackgroundWorkItem(
clt => LongRunningActionAsync(clt)
);
//Sample 4
//Action overload
//without lambda expression
HostingEnvironment.QueueBackgroundWorkItem(
await (Action)LongRunningAction
);
return View();
}
//Action overload's target
private void LongRunningAction(CancellationToken clt)
{
Task.Run(() => { Thread.Sleep(5000);
Debug.WriteLine("Action executed");
});
}
//Action overload's target
private async void LongRunningActionAsync(CancellationToken clt)
{
await Task.Run(() => { Thread.Sleep(5000);
Debug.WriteLine("Action async executed");
});
}
}
}
So what's the point of having a Task.Run
inside the Action?那么在 Action 中包含
Task.Run
有什么意义呢?
Your understanding is correct.你的理解是正确的。 Internally,
HostingEnvironment.QueueBackgroundWorkItem
delegates the execution to the thread pool (after doing some various registration work to keep track of the execution), so there's no benefit to starting yet another thread inside of the action.在内部,
HostingEnvironment.QueueBackgroundWorkItem
将执行委托给线程池(在执行一些各种注册工作以跟踪执行之后),因此在操作内部启动另一个线程没有任何好处。 It even defeats the whole purpose of HostingEnvironment.QueueBackgroundWorkItem
, since the methods are asynchronous and yet don't return a Task, and therefore the execution won't be tracked by ASP.NET.它甚至违背了
HostingEnvironment.QueueBackgroundWorkItem
的全部目的,因为这些方法是异步的,但不返回任务,因此 ASP.NET 不会跟踪执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.