Calling SubmitChanges() in LINQ-to-SQL from multiple threads
===

I have found similar threads on SO, but none that seem to address my exact issue.

Basically I have written a simple producer/consumer app using the .NET task parallel library.  The producer checks a database table for records on a 30 second interval.  When it finds records, it adds them to a `BlockingQueue`.  Meanwhile, I use `Task.Factory` to perform some actions on the records.

When actions are about to be taken on a record, I want to update a field on the record to indicate that it's already in queue.  This is so that if the producer checks for new records while the last batch is still being processed, it won't add an old entry back to the queue.

This issue that I'm running into is calling `SubmitChanges()` on my data context from multiple threads.  I *think* I'm running a race condition, but I'm not sure.

The error I get is `The operation cannot be performed during a call to SubmitChanges.`

**Producer Code:**
    
    BlockingCollection<QueuedMessage> workItems = new BlockingCollection<QueuedMessage>();

    System.Threading.Timer workItemTimer = new System.Threading.Timer((s) =>
        {
            var items = repository.GetQueuedMessages();

            foreach (var item in items)
            {
                workItems.Add(item);
            }
                    
        }, null, 0, 30000);

**Consumer Code:**

    while (workItems.TryTake(out queuedMessage, Timeout.Infinite, new CancellationToken()))
    {
        Task.Factory.StartNew((t) =>
            {
                var messageToSend = (QueuedMessage)t;

                repository.MarkQueuedMessageAsProcessing(messageToSend.Id);

                ...

                Do some stuff with messageToSend

                ....

        }, queuedMessage);
    }

**Repository Code:**

    var entity = DataContext.QueuedMessages.SingleOrDefault(m => m.Id == messageId);
    entity.ProcessingStarted = true;
    DataContext.SubmitChanges();

When I run this with a few queued messages, `DataContext.SubmitChanges()` will start throwing an exception with the message I mentioned earlier, `The operation cannot be performed during a call to SubmitChanges.`

Like I said, I *think* this is because I'm calling it from multiple threads, but I'm not sure how to work around this.

I tried changing the problematic line to:

    ThreadPool.QueueUserWorkItem(s => DataContext.SubmitChanges());

But the results are the same.