LINQ Concurrency

When using LINQ with multiple threads operations can be interrupted in the middle of everything. To handle this LINQ to SQL has this neat “Update Check” feature that checks is the record has been changed or deleted before a update record is submitted. Id this check fails a ChangeConflictException is thrown and we need to handle this. We might do as follows:

while(dataContext.GetChangeSet().Updates.Count > 0)
{
try
        {
            dataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
        }
        catch (ChangeConflictException)
        {
                  foreach(ChangeConflict conflict in dataContext.ChangeConflicts)
                  {
                             conflict.Resolve(RefreshMode.KeepChanges);    
                  }
        }
}

And presto! We have an update that will survive a multithreaded environment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: