【问题标题】:How to pass HttpContext to the new Thread c#如何将 HttpContext 传递给新线程 c#
【发布时间】: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


    【解决方案1】:

    您可以使用ParameterizedThreadStart 将参数传递给新线程

    var job = new Thread(async input =>
    {
        HttpContext httpContext = (HttpContext)input;
    
    });
    
    job.Start(HttpContext.Current)
    

    虽然我不建议将HttpContext 传递给新线程。这是一个好主意,因为HttpContext 不是线程安全的。同样,在您return "Accepted"; 之后,当前请求将完成并处理HttpContext。因此,您可能会在新线程中获得一些已处置的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多