Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of HttpContext

After a fair bit of Googling I have not found any authoritative, conclusive information regarding the thread safety of HttpContext.

I'm looking at a scenario such as:

public class AsyncHandler : IAsyncHttpHandler 
{
   void BeginProcessRequest(...)
   {
      // Spawn some tasks in parallel, provide them with current HttpContext as argument.
   }

   void EndProcessRequest(...) {...}
}

My (io bound) parallel tasks would want to access HttpContext, potentially at the same time.

Looking around at various posts it seems that this is safe, however, I'd like some actual evidence. Of course MSDN gives the usual "statics are threadsafe etc.", but this doesn't help other than I'd have to assume it's not threadsafe.

I've seen various posts on StackOverflow (such as here, or here, or here) but no real answer to this question.

With all the async work in .NET 4.5 it would seem a little strange if HttpContext is not threadsafe, however, if indeed it isn't so, are there any ways to make it so? I could think of:

  • Clone it (but this isn't so easy, although it doesn't seem impossible at first sight).
  • Wrap HttpContextBase and make this thread safe (hey, I'd call it HttpContextWrapperWrapper).

but this all feels a bit crappy and too much work.

EDIT: After looking into this in more detail, and some reflectoring later, I believe it does in fact not matter that HttpContext is not thread safe. I detailed this in this blog post. The gist is that using the correct SynchronizationContext in ASP.NET ensures that no more than one thread at a time will access the context.

like image 952
Marcus Avatar asked Nov 17 '12 17:11

Marcus


1 Answers

The HttpContext class is not thread-safe.

For example, the HttpContext.Items property is just a reference to an unsynchronized Hashtable - so this is clearly not thread-safe.

It's not clear from your question exactly what you want to share between the parallel tasks, but I would suggest you use an instance of your own thread-safe class to share state between the tasks rather than attempting to wrap an existing class.

like image 171
Joe Avatar answered Oct 18 '22 05:10

Joe