I have a multithreaded application that is using LinqToSql. One of the things I need to do is is grab a bunch of rows on behalf of a thread, e.g.:
dataContext.Connection.BeginTransaction()
var available = MyThings.Where(t => t.IsAvailable).Take(numberToTake);
// other validation stuff happens here, then:
foreach (var t in available) {
t.IsAvailable = false;
t.GrabbedBy = this;
dataContext.SubmitChanges();
}
dataContext.Connection.CommitTransaction();
Trouble is, that query in line 2 doesn’t seem to lock the MyThings table, because other threads appear to be able to grab the same rows that this thread has grabbed, which is obviously not a good thing. I cannot put a code lock around this block, because the different threads may be running in different memory spaces, possibly even different computers. But I do need to be able to lock those rows using a database-level transaction boundary to prevent anyone else grabbing them while I’m doing my validation stuff.
Is there any built-in way to do this with LinqToSql, short of making a “dummy” update to those rows in order to cement my grip on them in the transaction boundary?
You need to specify the IsolationLevel