简体   繁体   English

如何将 HttpContext 传递给新线程 c#

[英]How to pass HttpContext to the new Thread c#

I need to invoke my process and forget about it.我需要调用我的流程并忘记它。 I have a method which is able to invoke my process and return "Accepted" without waiting.我有一个方法可以调用我的流程并返回“已接受”而无需等待。 The problem is that I cannot access HttpContext inside the new thread (inside action).问题是我无法在新线程(内部操作)中访问 HttpContext 。 I would like to forward HttpContext from the main thread to the new one however it doesn't work.我想将 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
    }
}

You can pass parameters to a new thread with ParameterizedThreadStart您可以使用ParameterizedThreadStart将参数传递给新线程

var job = new Thread(async input =>
{
    HttpContext httpContext = (HttpContext)input;

});

job.Start(HttpContext.Current)

Although I don't recommend passing HttpContext to a new thread.虽然我不建议将HttpContext传递给新线程。 It's a good idea since HttpContext is not thread safe.这是一个好主意,因为HttpContext不是线程安全的。 Also after you return "Accepted";同样在您return "Accepted"; the current request will finish and it will dispose HttpContext .当前请求将完成并HttpContext So you might get some disposed objects in the new thread.因此,您可能会在新线程中获得一些已处置的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM