views:

83

answers:

2

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?

+4  A: 

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:

Heinzi
+1 very interesting, I didn't know about this thread switch in the early stages of request processing.
AnthonyWJones
+2  A: 

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.

AnthonyWJones