【发布时间】:2020-12-04 08:55:51
【问题描述】:
我需要调用我的流程并忘记它。我有一种方法可以调用我的流程并无需等待即可返回“已接受”。问题是我无法在新线程(内部操作)中访问 HttpContext 。我想将 HttpContext 从主线程转发到新线程,但是它不起作用。
private async Task<string> InvokeAsyncProcess(bool wait, Func<Task<Statistics>> action, string name)
{
var oldHttpContext = System.Web.HttpContext.Current;
if (wait)
{
Statistics stats = await action.Invoke();
return JsonConvert.SerializeObject(stats);
}
else
{
Thread job = new Thread(async f =>
{
try
{
System.Web.HttpContext.Current = oldHttpContext;
await LogService.LogAsync(LogCategory.Info, name, "Started in the background", null, null);
Statistics stats = await action.Invoke();
await LogService.LogAsync(LogCategory.Info, name, string.Format("Finished, returned data: {0}", JsonConvert.SerializeObject(stats)), null, null);
}
catch (Exception e)
{
await LogService.LogAsync(LogCategory.Error, name, "Error...", e, null);
}
});
job.Start();
Response.StatusCode = (int)HttpStatusCode.Accepted;
return "Accepted"; // Accepted = 202
}
}
【问题讨论】:
标签: c# asp.net asp.net-mvc multithreading httpcontext