gpt4 book ai didi

c# - Asp.Net 中 Task.Run 和 QueueBackgroundWorkItem 的区别

转载 作者:IT王子 更新时间:2023-10-29 03:59:03 25 4
gpt4 key购买 nike

使用

到底有什么区别
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 .如果你真的想测试发生了什么,你可以尝试 force a recycle .

关于c# - Asp.Net 中 Task.Run 和 QueueBackgroundWorkItem 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29938522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com