asp.net-core - 使用干净的 AsyncLocal 状态启动任务

标签 asp.net-core .net-core asp.net-core-1.1

在 ASP.NET Core 中,我使用的是 IHttpContextAccessor访问当前 HttpContext . HttpContextAccessor uses AsyncLocal<T> .

在一种情况下,我试图启动一个 Task从请求中,应该在请求结束后继续运行(长时间运行,后台任务),我试图将它从当前执行上下文中分离出来,以便 IHttpContextAccessor返回 null (否则我正在访问无效的 HttpContext )。

我试过 Task.Run , Thread.Start ,但每次,上下文似乎都会延续和 IHttpContextAccessor无论我尝试什么都返回旧的上下文(有时甚至是来自其他请求的上下文🤔)。

如何开始一个干净的任务 AsyncLocal状态,以便 IHttpContextAccessor返回 null ?

最佳答案

迟到的答案,但可能对其他人有用。您可以通过在提交任务时抑制 ExecutionContext 流来做到这一点:

ExecutionContext.SuppressFlow();

var task = Task.Run(async () => {
    await LongRunningMethodAsync();
});

ExecutionContext.RestoreFlow();
或更好:
using (ExecutionContext.SuppressFlow()) {
    var task = Task.Run(async () => {
        await LongRunningMethodAsync();
    });
}
这将防止在提交的任务中捕获 ExecutionContext。因此,它将具有“干净”的 AsyncLocal 状态。
如上所述,如果它是 CPU 密集型后台工作,我不会在 ASP.net 中执行此操作。

关于asp.net-core - 使用干净的 AsyncLocal 状态启动任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757932/

相关文章:

c# - 使用 ADFS 进行 Asp.net Core 身份验证。将按钮名称从 {wsfederation} 更改为我的首选名称

ssl - 如何使用新的 HTTPS 本地主机证书

c# - 多个.Include in Repository

linux - 带有 nginx 路由的 linux 上的 asp.net 核心不起作用

sql-server - 为什么 macOS 上的 .NET Core 项目无法连接到 SQL Server Express Docker 容器?

ASP.NET 核心 : how to set the requesttimeout for a single action/route?

c# - 手动解码 CodedInputStream 上的 Size

c# - if (false == true) 在内部抛出异常时执行 block

c# - 如何在 ASP.net Core 1.1 MVC 中将用户重定向到新 URL

asp.net-core - 完全兼容 ASP.NET Core 的 Glimpse 诊断平台