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.