使用Singleton模式到Linq到Sql数据上下文 [英] Using a Singleton pattern to Linq to Sql Data Context

查看:133
本文介绍了使用Singleton模式到Linq到Sql数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经有一个开放的问题,与此命令关联的数据读取器必须先关闭



特别在多任务环境中。大多数人都在说,原因是数据上下文不是线程安全的。使用DataContex作为每单位工作的一个。



请参考以下主题以获得最佳答案



多个线程的Linq-to-SQL数据上下文



但在我的情况下,我正在使用在Singleton模式中实现的另一个类调用A。该类的目的是以单例方式提供数据上下文对象。我正在维护此类的实例A作为派生类中的全局实例,并通过使用特定实例调用Datacontex。我的问题是,



我的方法调用是否会导致不受控制的内存增长?基于我的理解,单身份保持一个实例作为静态对象。如果我的假设是错误的,请给我很好的解释。



注意: / p>

任何方式我的方法调用也会抛出相同的异常。所以我确定在这种情况下也发生同样的问题。

解决方案

您的方法一般会导致问题。一个 DataContext 并不是单身人士。只要不要这样做。



即使 A 是一个单身,创建一个新的 DataContext A 之内的适当方法中,而不是将 DataContext 作为变量在 A 之内。 (您也可以考虑 A 是否应该是一个单身汉。)


I have some confusion in Linq to SQL.I am searching for an actual reason why Data context class gives follwing Exception some times .

"There is already an open data reader associated with this command which must be closed first

Specially in multitasking environment.Most people are saying that the reason is ,Data Context is not thread Safe.All are suggesting to use DataContex as one per unit of work.

Please refer following thread for best answer

Linq-to-SQL Data Context across multiple threads

But in my case,i am using another class call "A" which is implemented in Singleton pattern.Purpose of this class is ,provide Data context object in singleton manner.I am maintaining instance of this class "A" as global instance in derived class and calling to Datacontex by using particular instance.

My question is,

Will my method call cause uncontrolled memory growth ? based on my understanding,singleton maintaining one instance as static object .If my assumption is wrong ,please give me good explanation.

Note:

Any way my method call also throws same exception.So i am sure same problem is happen in this scenario also.

解决方案

Your approach will cause problems in general. A DataContext is not intended to be a singleton. Just don't do it.

Even if A is a singleton, create a new DataContext within the appropriate methods within A, rather than having a DataContext as a variable within A. (You might also want to consider whether A should really be a singleton in the first place.)

这篇关于使用Singleton模式到Linq到Sql数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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