本文介绍了如何将HttpContext传递给新线程C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用我的过程,然后忘记它.我有一种方法,该方法能够调用我的过程并返回已接受"消息.不用等待.问题是我无法在新线程内(内部操作)访问HttpContext.我想将HttpContext从主线程转发到新线程,但是它不起作用.

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). I would like to forward HttpContext from the main thread to the new one however it doesn't work.

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
    }
}

推荐答案

您可以使用 ParameterizedThreadStart

You can pass parameters to a new thread with ParameterizedThreadStart

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

});

job.Start(HttpContext.Current)

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

Although I don't recommend passing HttpContext to a new thread. It's a good idea since HttpContext is not thread safe. Also after you return "Accepted"; the current request will finish and it will dispose HttpContext. So you might get some disposed objects in the new thread.

这篇关于如何将HttpContext传递给新线程C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 03:48