20

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?

Tim Tom
  • 2,082
  • 6
  • 25
  • 39

3 Answers3

35

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);
nemesv
  • 133,215
  • 15
  • 395
  • 348
  • 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. – Giedrius Apr 30 '13 at 15:02
  • 2
    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 http://stackoverflow.com/questions/8925227/access-httpcontext-current-from-threads – Rory Dec 30 '15 at 17:22
8

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.

David Tischler
  • 2,602
  • 21
  • 13
0

As David pointed out, HttpContext.Current will not work all the time. In my case, about 1 of 20 time, CurrentContext will be null. End up with below.

string UserName = Context.User.Identity.Name;

System.Threading.Tasks.Task.Factory.StartNew(() =>
{
    UserName ...
}
Community
  • 1
  • 1
Rm558
  • 3,263
  • 3
  • 29
  • 37