I’m using LINQ to SQL and after I submit some changes I want to spawn a thread which looks through all the changes and updates our lucene index as necessary. My code looks vaguely like:
(new Thread(() => { UpdateIndex(context.GetChangeSet()); }).Start();
Sometimes though I get an InvalidOperationException, which I think is because context.GetChangeSet() is not thread-safe, and so if the change set is modified in one thread while another thread is enumerating through it, problems arise.
Is there a “thread-safe” version of GetChangeSet()? Or some way I can do ChangeSet.clone() or something?
Instance members of the DataContext class are not thread-safe.
In order to avoid race conditions you should invoke the DataContext.GetChangeSet method from the same thread that makes the modifications tracked by the DataContext instance. For example:
This assumes that the Insert and Delete methods are being called on a given instance of the CustomerDao class from a single thread.