【问题标题】:Getting HttpContext in a task在任务中获取 HttpContext
【发布时间】:2015-12-03 19:47:56
【问题描述】:

我在使用任务调用的方法中丢失了 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
    }

【问题讨论】:

  • 如果您将DoSomething 更改为接受HttpContext 作为参数会怎样?
  • 当然,但我希望有更好的方法
  • 我认为没有比这更好的方法了。
  • @johnsmith 只有在处理请求的线程中才能获取上下文。在任何其他线程中,您都会得到 null。

标签: c# asp.net .net-4.0 task


【解决方案1】:

你需要传入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
}

【讨论】:

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