Thread safe Entity Framework 6

懵懂的女人 提交于 2019-12-03 02:45:40

I think you are facing an architectural issue. What you describes is an application where UI directly uses EF objects, and it breaks the "separation of concerns" paradigm.

On my side, I use customs thread-safe caches on a Model layer, letting everything happens on the Model layer. I implemented thread-safety on my cache with the well-known AsyncLock.

DbContext objects, and every EF CRUD related operations have a very limited lifetime. Each CRUD Operation instantiate it's own DbContext, and returns Model Objects to the cache, then, contexts are garbage collected. My applications uses caches as an abstraction layer, and caches uses EF as a DB abstraction layer.

For example, exploring attached properties on Objects, is done by implementing custom methods on the Model layer, which takes the object Id as parameter, and returns a list of related objects to the cache. The UI asks the Cache, then the Cache asks EF, then once available, the call made to the cache returns objects to the UI. Simple as that.

EntityFramework is not designed to be thread safe, so there's no way to work with it in a multi-threaded way. (EF thread safety)

Instead of having parallel access to you DbContext, you have to build a Model layer which can be accessed in a multi-threaded way. And your model can make multiple parallel calls to you DB, but keep in mind that each call must instantiate and keep it's own DbContext. At the end of each call, the related DbContext must be disposed.

DbContext are really fast to instantiate, the only downside is the network latency. That's why a memory cache is a good idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!