Using an HTTPContext across threads

此生再无相见时 提交于 2019-11-28 12:00:49
meandmycode

Whilst the HttpContext is designed to handle a context that isn't thread specific (because the http context can start on one thread and finish on another), it isn't implicitly thread safe.

Essentially the problem is you are doing something that isn't intended, these requests would be multiple generally and each have their own assigned HttpApplication to fulfill the request, and each have their own HttpContext.

I really would try and let the asp.net infrastructure delegate the requests itself.

Your co workers are right, if one thread locks a resource and another thread attempts to use it then your thread pool goes boom! Not very good outcome. Most people resolve this by creating new objects and passing them into paramaterized threads. If you absolutely need to use the same object then you must implement some code that first checks to see if the resource is being used by another thread and then waits a little while before checking again. An example would be to create a IsInUse bool that you always check first, then your thread sets it to true if it is using that resource, then false when it is done, preventing other threads from attempting to use the underlying resource (your httpContext). I hope this helps.

Since HttpContext is part of the .Net library, I would expect that all static functions are threadsafe but any non-static members are not threadsafe when calling against the same instance of the object. So hopefuly next time you will anticipate that sharing the HttpContext instance across threads would have problems.

Is there a way you can decouple the operations you need to carry out in parallel from the HttpContext? If they are just loading data and writing to CSV format, that code has no necessary dependency on ASP.NET user control or page lifecycle. Once that dependency is removed, you can implement the page with an asynchronous HttpHandler, running the parallel operations during between IHttpHandler.BeginProcessingRequest() and IHttpHandler.EndProcessingRequest().

Darius

I would ensure that any time you access the HttpContext.Current.Items collection, that you use a Monitor lock (C#)/SyncLock(VB) block on the HttpContext.Current.Items.SyncRoot object to wrap your calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!