2015-12-03 58 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 
}