开发者

Asynchronous HTTP Handler and using HttpContext in a background thread?

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 becaus开发者_开发问答e 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜