2015-12-03 55 views
0

我在使用任务调用的方法中丢失了HttpContext。谷歌搜索似乎表明这个代码应该工作。任何想法我可能在这里做错了吗?在任务中获取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 
    } 
+0

,如果你有什么改变'DoSomething'接受一个'HttpContext'作为参数? – mason

+0

当然,但我希望有更好的方式 – BKS

+0

我不认为会有比这更好的方式。 – Amy

回答

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 
}