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.
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?
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".
It is stored in the memory of the server and the value is available for the entire lifetime of the request.
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.
The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With