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 b开发者_运维技巧e 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();
}
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.
string connectionString = "Data Source=MSSQL1;" +
"Initial Catalog=AdventureWorks;Integrated Security=SSPI" +
"MultipleActiveResultSets=True";
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.
精彩评论