在网站上使用 Linq to SQL 时出现异常。已经有开放的数据阅读器
在 ASP.NET 网站上,我使用 LINQ to SQL 来获取数据。此操作有点长(可能长达 3 秒),并且用户通常会第二次单击链接
已经有一个与此命令关联的打开的 DataReader 必须先关闭它。
我查看了 使用 LINQ 时 DataReader 已经打开 和其他类似的线程,但我确实这样做不明白如何处理/解决这个问题。
我应该完全摆脱 LINQ to SQL 吗?处理这个问题的正确方法是什么?
编辑:
我从Page_Load调用的代码
using (var wdc = new WebDataContext())
{
// Expensive operation, increase timeout
wdc.CommandTimeout = 120;
// First need to update data for this customer
wdc.Web_WrkTrackShipment_Update((int)this.Parent.ProviderUserKey, sessionId);
// Return set of this data based on parameters.
return wdc.Web_WrkTrackShipment_Load(sessionId, pageNo, pageSize, searchCriteria, dateFrom, dateTo, ref pageCount_Null).ToList();
}
On a ASP.NET website I use LINQ to SQL to get data. This operation somewhat long (can be up to 3 seconds) and often user clicks on a link second time
There is already an open DataReader associated with this Command
which must be closed first.
I looked at DataReader already open when using LINQ and other similar threads but I do not understand how to handle/fix this.
Should I get rid of LINQ to SQL alltogether? What is a proper way to handle this?
EDIT:
Code that I call from Page_Load
using (var wdc = new WebDataContext())
{
// Expensive operation, increase timeout
wdc.CommandTimeout = 120;
// First need to update data for this customer
wdc.Web_WrkTrackShipment_Update((int)this.Parent.ProviderUserKey, sessionId);
// Return set of this data based on parameters.
return wdc.Web_WrkTrackShipment_Load(sessionId, pageNo, pageSize, searchCriteria, dateFrom, dateTo, ref pageCount_Null).ToList();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过设置多个活动结果集( MARS) 在连接字符串中设置为 true。请注意,这可能表明存在 N+1 连接问题,这实际上取决于查询。
You can fix this by setting Multiple Active Result Sets(MARS) to true in the connectionstring. Note that this might indicate a N+1 join problem, it really depends on the query.
我怀疑,根本原因是 DataContext 不是线程安全的。不同的请求在不同的线程上运行。
不要在线程之间共享 DataContext。可以在 BeginRequest 上启动一个并在 EndRequest 上关闭它 - 或者在需要时在本地创建一个,并将其包装在
using
语句中,以便在您的代码使用完它后立即将其释放。I suspect, yhe underlying reason is DataContext not being thread-safe. Different requests run on different threads.
Don't share your DataContext between threads. Either start one on BeginRequest and close it on EndRequest - or create one locally whenever you need it, and wrap it in a
using
statement so it is immediately disposed when your code has finished using it.