Asynchronous HTTP handler and using an HttpContext in a background thread?

I read the Walkthrough: Creating an Asynchronous HTTP Handler and noticed that they are passing the HttpContext from the handler thread and using it in WaitCallback , which runs on the background thread. It calls such calls as _context.Response.Write() . Do I correctly believe that this does not violate the fact that the HttpContext is not thread safe because the handler thread will not use it after starting async?

In addition, Using HTTPContext for streams contains some useful information about HttpContext and streams. Are all HttpContext not thread safe, or just elements like Response ? Can multiple background threads access the Items property, if only in read mode?

+4
source share
1 answer

HttpContext and all its properties are not thread safe, so you have to be very careful. Reading data from different streams at the same time may not harm, but you must be sure that no write operations are occurring. However, even if you are sure that the Items property is not changed, I would prefer to make a copy and provide it to background threads. This clearly indicates intent and saves you from discussion 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 manages the threads and ensures that only one thread processes the request. It would be different if, for example, you deployed a new thread manually (using the thread pool or new Thread() ) and supplying HttpContext for this thread, continuing execution.

+4
source

Source: https://habr.com/ru/post/1300863/


All Articles