How do I access HttpContext.Current in Task.Factory.StartNew?
Task.Factory.Start
will fire up a new Thread
and because the HttpContext.Context
is local to a thread it won't be automaticly copied to the new Thread
, so you need to pass it by hand:
var task = Task.Factory.StartNew( state => { var context = (HttpContext) state; //use context }, HttpContext.Current);
You could use a closure to have it available on the newly created thread:
var currentContext = HttpContext.Current;Task.Factory.Start(() => { // currentContext is not null here});
But keep in mind that a task can outlive the lifetime of the HTTP request and could lead to funny results when accessing the HTTPContext after the request has completed.