在任务中获取 HttpContext

Getting HttpContext in a task

我在使用任务调用的方法中丢失了 HttpContext。谷歌搜索似乎表明这段代码应该有效。知道我在这里做错了什么吗?

    void ThisMethodIsCalledFromASPNet()
    {
        var context = System.Web.HttpContext.Current;   // Here I am getting valid context

        Task.Factory.StartNew( () => DoSomething(), CancellationToken.None, TaskCreationOptions.None, 
TaskScheduler.FromCurrentSynchronizationContext());
    }

    void DoSomething()
    {
        var context = System.Web.HttpContext.Current;   // Here I am getting null
    }

您需要传入 HttpContext:

void ThisMethodIsCalledFromASPNet()
{
    Task.Factory.StartNew( 
        ctx => DoSomething((HttpContext)ctx),
        System.Web.HttpContext.Current,
        CancellationToken.None, 
        TaskCreationOptions.None, 
        TaskScheduler.FromCurrentSynchronizationContext());
}

void DoSomething(HttpContext ctx)
{
    // ctx is your HttpContext
}