Is it safe to store an ObjectContext in a thread static variable in ASP.NET?

眉间皱痕 提交于 2019-12-07 14:00:05

问题


I've read that I should store an ObjectContext in HttpContext.Current in order to share my ObjectContext across different services/repositories that are called in a request. I'm wondering if it is safe to use an ObjectContext with the [ThreadStatic] attribute on a static class variable instead. Is that a safe thing to do? Is each request processed in its own thread?


回答1:


No, there can be multiple requests in the same thread and, more importantly, one request can be processed in multiple threads. This is called thread agility, and you will run into problems when you store stuff in thread-static variables instead of the Context: When ASP.NET moves from one thread to another during the same request, the HttpContext is still accessible, but the thread-static variable is not.

Some links with further information:

  • CallContext vs ThreadStatic (related question)
  • http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html (blog entry with details)



回答2:


A single thread is used to process a request and no other request will use that thread until the existing request is complete. However you need to consider how you make sure that items in the your context object are disposed of even when there is something exceptional happening. Once the thread is finished with a request for what ever reason it will be re-used to process other requests. You don't want state from a previous request leaking into the next.



来源:https://stackoverflow.com/questions/1785119/is-it-safe-to-store-an-objectcontext-in-a-thread-static-variable-in-asp-net

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