9

I'm having issues with Entity Framework and multiple threads and I am wondering if there is a solution that keeps the ability to lazy load. From my understanding the data context is not thread safe which is why when I have multiple threads using the same data context I get various data readers error. The solution to this problem is to use a separate data context for each connection to the database and then destroy the data context. Unfortunately destroying my data context then prevents me from doing lazy loading.

Is there a pattern to allow me to have a shared context across my application, but still properly handle multiple threads?

ctrlalt313373
  • 3,935
  • 7
  • 36
  • 40

1 Answers1

10

No, there is no such solution. Your choices in multithreaded application are:

  • Context per thread
  • Single context producing unproxied detached entities (no lazy loading, no change tracking) with synchronization for each access to that context.

Doing the second approach with proxied attached entities is way to disaster. It would require to detect all hidden interactions with the context and make related code also synchronized. You will probably end with single threaded process running in multiple switching threads.

Phil Carson
  • 884
  • 8
  • 18
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • +1 because this is technically correct, but: Sharing one context across an entire application is a problem even with only one thread. The context should be a unit of work and short-lived. – Craig Stuntz Aug 24 '11 at 14:01
  • @Craig: That is correct. I didn't mean one context instance for the whole application but one context for multiple threads working on single "logical operation". I'm not sure if it is still unit of work if entities must be detached. – Ladislav Mrnka Aug 24 '11 at 14:12
  • Thanks. That's what I figured the answer would be. – ctrlalt313373 Aug 26 '11 at 12:59
  • In the first scenario, What happens if you want to save a model which has been created on another dbcontext? – Hossein Shahdoost May 15 '16 at 10:56