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?
views:
83answers:
2No, 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:
- http://stackoverflow.com/questions/273301/callcontext-vs-threadstatic (related question)
- http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html (blog entry with details)
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.