5

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.

Community
  • 1
  • 1
Marcus
  • 5,987
  • 3
  • 27
  • 40
  • 2
    I don't think it's a clear cut situation - I think you'd need to elaborate on what modifications you're thinking of performing - I certainly don't know what I'd *expect* to happen if multiple threads tried to set/reset the same response header. – Damien_The_Unbeliever Nov 17 '12 at 17:26
  • I was thinking mostly of reading, such as query parameters, rather than setting things like headers. I agree I wouldn't know what I'd expect to happen. Also writing to a response stream at the same time wouldn't really make sense. – Marcus Nov 17 '12 at 19:33

1 Answers1

8

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.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • Simple but convincing answer, this does indeed seem the way to go. Even though Items is an IDictionary (so *could* be thread safe), it does in fact seem to be implemented by a HashTable whose IsSynchronized property returns false. – Marcus Nov 17 '12 at 20:30