Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous HTTP Handler and using HttpContext in a background thread?

Tags:

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?

like image 984
Kevin Hakanson Avatar asked Feb 10 '10 13:02

Kevin Hakanson


1 Answers

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.

like image 63
Steven Avatar answered Nov 15 '22 05:11

Steven