本文介绍了实体框架+多线程+延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Entity Framework和多个线程中遇到问题,我想知道是否有一个能够延迟加载的解决方案。从我的理解数据上下文不是线程安全的,这就是为什么当我有多个线程使用相同的数据上下文时,我得到各种数据读取器错误。解决这个问题的方法是为数据库的每个连接使用单独的数据上下文,然后破坏数据上下文。不幸的是摧毁了我的数据上下文,从而阻止我进行延迟加载。

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:


  • 每个线程的上下文

  • 单个上下文生成未经管理的分离实体没有延迟加载,没有更改跟踪)同步每次访问该上下文。

使用代理附加实体执行第二种方法是到灾难它需要检测与上下文的所有隐藏的交互,并使相关代码也同步。您可能会以多个切换线程运行的单线程进程结束。

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.

这篇关于实体框架+多线程+延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:30