在 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/