title: Calling SubmitChanges() in LINQ-to-SQL from multiple threads
body: <p>I have found similar threads on SO, but none that seem to address my exact issue.</p>
  
  <p>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 <code>BlockingQueue</code>.  Meanwhile, I use <code>Task.Factory</code> to perform some actions on the records.</p>
  
  <p>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.</p>
  
  <p>This issue that I'm running into is calling <code>SubmitChanges()</code> on my data context from multiple threads.  I <em>think</em> I'm running a race condition, but I'm not sure.</p>
  
  <p>The error I get is <code>The operation cannot be performed during a call to SubmitChanges.</code></p>
  
  <p><strong>Producer Code:</strong></p>
  
  <pre><code>BlockingCollection&lt;QueuedMessage&gt; workItems = new BlockingCollection&lt;QueuedMessage&gt;();
  
  System.Threading.Timer workItemTimer = new System.Threading.Timer((s) =&gt;
      {
          var items = repository.GetQueuedMessages();
  
          foreach (var item in items)
          {
              workItems.Add(item);
          }
  
      }, null, 0, 30000);
  </code></pre>
  
  <p><strong>Consumer Code:</strong></p>
  
  <pre><code>while (workItems.TryTake(out queuedMessage, Timeout.Infinite, new CancellationToken()))
  {
      Task.Factory.StartNew((t) =&gt;
          {
              var messageToSend = (QueuedMessage)t;
  
              repository.MarkQueuedMessageAsProcessing(messageToSend.Id);
  
              ...
  
              Do some stuff with messageToSend
  
              ....
  
      }, queuedMessage);
  }
  </code></pre>
  
  <p><strong>Repository Code:</strong></p>
  
  <pre><code>var entity = DataContext.QueuedMessages.SingleOrDefault(m =&gt; m.Id == messageId);
  entity.ProcessingStarted = true;
  DataContext.SubmitChanges();
  </code></pre>
  
  <p>When I run this with a few queued messages, <code>DataContext.SubmitChanges()</code> will start throwing an exception with the message I mentioned earlier, <code>The operation cannot be performed during a call to SubmitChanges.</code></p>
  
  <p>Like I said, I <em>think</em> this is because I'm calling it from multiple threads, but I'm not sure how to work around this.</p>
  
  <p>I tried changing the problematic line to:</p>
  
  <pre><code>ThreadPool.QueueUserWorkItem(s =&gt; DataContext.SubmitChanges());
  </code></pre>
  
  <p>But the results are the same.</p>