Tim Tom Tim Tom - 1 year ago 242
ASP.NET (C#) Question

How do I access HttpContext.Current in Task.Factory.StartNew?

I want to access HttpContext.Current in my asp.net application within

Task.Factory.Start(() =>{
//HttpContext.Current is null here

How can I fix this error?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download