Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the HttpContext properties when it returns null?

Tags:

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?

like image 289
makstaks Avatar asked Feb 09 '09 18:02

makstaks


People also ask

Why HttpContext current is null?

Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

Where is HttpContext items stored?

It is stored in the memory of the server and the value is available for the entire lifetime of the request.

What is HttpContext item?

An HttpContext object will encapsulate specific details of a single HTTP request. Properties of this class include the Request object, the Response object, the Session object, and an AllErrors property which keeps an array of Exception objects accrued during the current request.

Is HttpContext current items thread safe?

The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.


2 Answers

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.

like image 181
Tamas Czinege Avatar answered Oct 24 '22 16:10

Tamas Czinege


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.

like image 36
MatthieuGD Avatar answered Oct 24 '22 15:10

MatthieuGD