简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM