跨多个线程的Linq-to-SQL DataContext [英] Linq-to-SQL DataContext across multiple threads
问题描述
如何跨多个线程处理Linq-to_SQL DataContext?
How do I handle a Linq-to_SQL DataContext across multiple threads?
我应该创建一个全局静态DataContext以便所有线程在最后使用并提交更改,还是应该为每个线程创建一个Context并将该实例用于该线程中的所有内容?
Should I be creating a global static DataContext that all the threads use and commit changes at the very end or should I create a Context per thread and use that instance for everything inside that thread?
推荐答案
DataContext
不是线程安全的;直接从多个线程使用它会导致#fail;具有全局静态数据上下文将导致#fail ,并且将导致不受控制的内存增长(数据上下文包括身份管理器和获取的每个对象的更改跟踪器;这仅是 grows 随着时间的流逝,将有更多的物体被触摸)
DataContext
is not thread safe; using it directly from multiple threads would cause #fail; having a global static data-context would cause #fail and would cause uncontrolled memory growth (the data-context includes an identity manager and change tracker for every object fetched; this only grows over time, as more objects are touched)
理想情况下,数据上下文应用于一个工作单元;旋转一个做某事(在范围内绑定-即不是整个应用程序生命周期),并进行处置.因此,海事组织的真正答案是将其与该工作单元联系起来".只有您知道应用程序中的内容.它可以是单个方法,也可以是网页上的页面请求,也可以是服务中的计时器滴答".谁知道...
Data context should ideally be used for a unit of work; spin one up; do something (that is bound in scope - i.e. not the entire app lifetime), and dispose it. So IMO the real answer here is "tie it to that unit of work". Only you can know what that is in your application; it could be a single method, it could a page request on a web page, it could be a timer "tick" in a service. Who knows...
这篇关于跨多个线程的Linq-to-SQL DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!