且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Singleton模式到Linq到Sql数据上下文

更新时间:2023-02-01 07:41:24

您的方法一般会导致问题。一个 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.)