Question

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.

Question

How do I create a new thread so that HttpContext.Current is not null? Or is there another way I can access the Cache, Server, and Request objects?

Was it helpful?

Solution

I'd try not to hold a reference to an object that depends on 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 till your task is finished. And maybe the Request/Context/Session is terminated while your thread is not.

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

OTHER TIPS

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.

1- Add bottom code in <system.serviceModel> in Web.config file:

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> 

2- Add bottom code after NameSpace in web service file:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

3- Rebuild web part project. Done!

reference

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top