Using an HTTPContext across threads Using an HTTPContext across threads multithreading multithreading

Using an HTTPContext across threads


Whilst the HttpContext is designed to handle a context that isn't thread specific (because the http context can start on one thread and finish on another), it isn't implicitly thread safe.

Essentially the problem is you are doing something that isn't intended, these requests would be multiple generally and each have their own assigned HttpApplication to fulfill the request, and each have their own HttpContext.

I really would try and let the asp.net infrastructure delegate the requests itself.


Your co workers are right, if one thread locks a resource and another thread attempts to use it then your thread pool goes boom! Not very good outcome. Most people resolve this by creating new objects and passing them into paramaterized threads. If you absolutely need to use the same object then you must implement some code that first checks to see if the resource is being used by another thread and then waits a little while before checking again. An example would be to create a IsInUse bool that you always check first, then your thread sets it to true if it is using that resource, then false when it is done, preventing other threads from attempting to use the underlying resource (your httpContext). I hope this helps.


Since HttpContext is part of the .Net library, I would expect that all static functions are threadsafe but any non-static members are not threadsafe when calling against the same instance of the object. So hopefuly next time you will anticipate that sharing the HttpContext instance across threads would have problems.

Is there a way you can decouple the operations you need to carry out in parallel from the HttpContext? If they are just loading data and writing to CSV format, that code has no necessary dependency on ASP.NET user control or page lifecycle. Once that dependency is removed, you can implement the page with an asynchronous HttpHandler, running the parallel operations during between IHttpHandler.BeginProcessingRequest() and IHttpHandler.EndProcessingRequest().