I have a table, we\'ll call Users
. This table has a single primary key defined in SQL Server - an autoincrement int ID
.
Sometimes, my LINQ
I had this Issue as well and solved it.
Now I understand the error was wrong usage of Linq Data Context, but maybe my experience can still help others understand why they get this error.
Linq Data Context is not meant for running simultaneously. Therefore creating multiple tasks running async is not ideal. Inspect following sample code to understand the issue:
using(var ctx = new LinqDataContext())
{
List tasks = new List();
for(int i=0;i<1000;i++)
{
var task = Task.Run(() => {
var customer = ctx.Customers.SingleOrDefault(o => o.Id == i);
customer.DoSomething();
}
tasks.Add(task);
}
Task.WaitAll(tasks);
}
In my scenario, I was passing the data context as a parameter in a longer call stack, and calling async methods along the way. So it wasn't as obvious as above example. But maybe this can help someone else anyhow :-)