使用LINQ时DataReader已经打开

使用LINQ时DataReader已经打开

问题描述:

我有一个包含静态字段的静态类,该静态字段引用了DataContext的包装对象.

I've got a static class containing a static field which makes reference to a wrapper object of a DataContext.

当我们创建dbml文件&时,DataContext基本上是由Visual Studio生成的.包含我们数据库中每个存储过程的方法.

The DataContext is basically generated by Visual Studio when we created a dbml file & contains methods for each of the stored procedures we have in the DB.

我们的类基本上具有一堆静态方法,可以触发这些存储的proc方法和&然后根据LINQ查询返回一个数组.

Our class basically has a bunch of static methods that fire off each of these stored proc methods & then returns an array based on a LINQ query.

示例:

public static TwoFieldBarData[] GetAgesReportData(string pct)
        {
                return DataContext
                .BreakdownOfUsersByAge(Constants.USER_MEDICAL_PROFILE_KEY, pct)
                .Select(x => new TwoFieldBarData(x.DisplayName, x.LeftValue, x.RightValue, x.TotalCount))
                .ToArray();
        }

我们偶尔会出现以下错误:

Every now and then, we get the following error:

已经有一个打开的DataReader 与此命令相关联的 必须关闭冷杉

There is already an open DataReader associated with this Command which must be closed firs

这是断断续续发生的,我对正在发生的事情感到好奇.我的猜测是,当一个方法执行与下一个方法触发之间存在一定的滞后时,它将锁定DataContext并引发错误.

This is happening intermittently and I'm curious as to what is going on. My guess is that when there's some lag between one method executing and the next one firing, it's locking up the DataContext and throwing the error.

是否可以将每个DataContext LINQ调用包装在lock(){}中以获得该类型的排他性并确保其他请求排队?

Could this be a case for wrapping each of the DataContext LINQ calls in a lock(){} to obtain exclusivity to that type and ensure other requests are queued?

DataContext并不意味着使用寿命长,并且绝对不打算与多个线程一起使用.

DataContext is not meant to be long-lived, and definitely is not meant to be used with multiple threads.

静态成员是长期存在的,并且可以被多个线程访问.冲突可能是您问题的根源.

A static member is long-lived and is accessed by multiple threads. That conflict could be the root of your problem.