Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework + Multiple Threads + Lazy Load

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?

like image 998
ctrlalt313373 Avatar asked Aug 24 '11 13:08

ctrlalt313373


1 Answers

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.

like image 96
Ladislav Mrnka Avatar answered Nov 01 '22 00:11

Ladislav Mrnka