良好的建议,以在多线程程序中使用EF? [英] Good advices to use EF in a multithread program?

查看:1189
本文介绍了良好的建议,以在多线程程序中使用EF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你有一些很好的建议使用EF在多线程程序?

Have you got some good advices to use EF in a multithread program ?

我有2层:

  • 在一个EF层读取/写入我的数据库
  • 在多线程服务,它使用我的实体(读/写),并提出了一些计算(我使用任务并行库在框架中)

我如何同步我的目标环境中的每个线程? 你知道一个很好的模式,使其工作?

How can I synchronize my object contexts in each thread ? Do you know a good pattern to make it work ?

推荐答案

忠告是 - 只是不要: - ) EF勉强设法生存的一个线程 - 野兽的本性

Good advice is - just don't :-) EF barely manages to survive one thread - the nature of the beast.

如果你绝对必须使用它,使最轻的DTO-S,接近OC只要你有数据,重新包装数据,产卵你的线程只是做计算,不出意外,等到他们都做了,然后创建另一个OC和转储数据返回到数据库,它调和等。

If you absolutely have to use it, make the lightest DTO-s, close OC as soon as you have the data, repack data, spawn your threads just to do calculations and nothing else, wait till they are done, then create another OC and dump data back into DB, reconcile it etc.

如果另一个主线程(一个通过TPL派生ñ计算线程)需要知道当一些疗法线程完成火灾事件,只是设置一个标志中的其他线程,然后让它的code检查标志在它的循环,并通过创造新的业主立案法团,然后核对数据,如果有反应。

If another "main" thread (the one that spawns N calculation threads via TPL) needs to know when some ther thread is done fire event, just set a flag in the other thread and then let it's code check the flag in it's loop and react by creating new OC and then reconciling data if it has to.

如果您的情况比较简单,你可以适应这一点 - 关键是,你只能设置一个标志,让当它准备另一个线程反应。这意味着,它是在一个稳定的状态,已经完成了一轮不管它是做和可以做的事情,而不用担心竞态条件。复位标志(一个int)与interchaged操作,并保持一定时间的数据,以确保您的线程不会在一定时间T再次做出反应 - otherwire他们可以用自己的一生只是查询数据库

If your situation is more simple you can adapt this - the key is that you can only set a flag and let another thread react when it's ready. That means that it's in a stable state, has finished a round of whatever it was doing and can do things without risking race conditions. Reset the flag (an int) with interchaged operations and keep some timing data to make sure that your threads don't react again within some time T - otherwire they can spend their lifetime just querying DB.

这篇关于良好的建议,以在多线程程序中使用EF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆