views:

288

answers:

1

I was reading Walkthrough: Creating an Asynchronous HTTP Handler and noticed they pass the HttpContext from the handler thread and use it in a WaitCallback which runs on a background thread. It makes calls like _context.Response.Write(). Am I correct in assuming that this doesn't violate the fact that HttpContext is not thread safe because the handler thread will not be using it after the async work has started?

Also, Using an HTTPContext across threads has some good information about HttpContext and threads. Is all of HttpContext not thread safe, or just items like Response? Can multiple background threads access the Items property, if only in read mode?

+1  A: 

The HttpContext and all its properties are not thread safe, so you should be very careful. Reading data simultaneously from different threads can do no harm, but you have to be sure that there are no write operations happening. Still, even when you're sure the Items property is not changed, I'd prefer to make a copy and supply that to the background threads. That communicates clearly the intend and saves you from having discussions during code reviews or people reevaluating whether this code is really thread safe.

Now about using HttpContext in asynchronous requests; Accessing the HttpContext from different threads would be dangerous, but in this case ASP.NET controls the threads and makes sure that only one thread is processing the request. It would be different when you, for instance, spin up a new thread manually (by using the thread pool or new Thread()) and supplying HttpContext to that thread, while continuing execution.

Steven