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

17,847

Solution 1

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);

Solution 2

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.

Share:
17,847
Tim Tom
Author by

Tim Tom

Updated on June 03, 2022

Comments

  • Tim Tom
    Tim Tom almost 2 years

    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?

  • Giedrius
    Giedrius about 11 years
    interestingly enough, that does work strange for me. For example User property of HttpContext becomes null after entering the thread, although it had value in HttpContext.Current.
  • The Muffin Man
    The Muffin Man almost 9 years
    I like using this way instead of passing in a state object and casting the items out into individual variables... messy.
  • irag10
    irag10 over 8 years
    Yes, it's worth noting that using a reference to HttpContext.Current might work a lot of the time but it's not recommended and it's likely to fail at times. ASP runtime may clean up the object when the http request is done and then you'll find things like context.Items[x] doesn't contain what you put there earlier. See also stackoverflow.com/questions/8925227/…
  • sirdank
    sirdank over 5 years
    By funny results, do you just mean old data inside the task's scope?