views:

4526

answers:

5

I am doing some asynchronous work on a separate thread using:

ThreadPool.QueueUserWorkItem(...)

and in this separate thread, I need to call HttpContext.Current so that I can access:

HttpContext.Current.Cache
HttpContext.Current.Server
HttpContext.Current.Request

however, HttpContext.Current is null when I create this separate thread.

My question is, how do I create a new thread so that HttpContext.Current is not null,

or if that is not possible, is there another way I can access the Cache, Server, and Request objects?

Thanks.

+15  A: 

You can access the ASP.NET cache with HttpRuntime.Cache even when you don't have a HttpContext, but unfortunately you cannot access Server or Request.

If you think about it, this make sense - you are not serving any page so you don't have a request.

DrJokepu
Good to know, this is what I needed for my particular conundrum, thanks!
MrBoJangles
Thumbs up! (Y). HttpRuntime.Cache helped saving my time alot. thanks
Zain Shaikh
A: 

If the separate thread is trying to access those objects, then yes they will be null. Those objects are scoped at the thread level. If you want to use them in a new thread you will have to pass them into the method/class where you need them.

Typically ASP.Net doesn't allow you to spawn new threads... Here is a post on the subject.

Here is a nice write up on threading in ASP.NET from MSDN.

Chuck Conway
The post on not creating threads in ASP.Net says nothing of the sort. It simply states you shouldn't use the ThreadPool to create your threads, and that you should manager them yourself.
Kibbee
+9  A: 

I'll try not to hold a reference on an object which depends of the ASP.NET stack like the HttpContext. If you need to do some work in a different thread it's because you don't want to wait in the ASP.NET one that your task is finished ? And maybe the Request/Context/Session is terminated when your thread is not.

You should pass an object with the data needed for your thread.

Matthieu
A: 

For HttpContext.Server services you can use HttpServerUtility class. For the Cache you can use HttpRuntime.Cache, as it has been said above. For the request object you can pass the data from the Request to the thread when it is created. Things like Request.QueryString or Request.Form... or whatever.

Andrei Rinea
To initiate an instance of HttpServerUtility outside of a web request, use: new HttpApplication().Server(via http://britishinside.com/archive/2005/08/20/HttpServerUtility.aspx)Some features won't work though. For example, Server.MapPath doesn't. But as a workaround use System.Web.Hosting.HostingEnvironment.MapPath instead.
Mufasa
A: 

There is a thread pool implementation here that provides propagation of the calling thread's HTTP context. I haven't used it yet but I plan to.

Andy Johnson