title: Multi-threading with Linq to SQL
body: <p>I am building an application which requires me to make use of DataContext's inside threads. My application keeps throwing <code>InvalidOperationException</code>'s similar to:</p>
  
  <p><code>There is already an open DataReader associated with this Command which must be closed first</code></p>
  
  <p><code>ExecuteReader requires an open and available Connection. The connection's current state is connecting</code></p>
  
  <p>These exceptions are intermittant.</p>
  
  <p>Here is a snippet of my code:</p>
  
  <pre><code>var repo = new Repository();
  var entities = repo.GetAllEntities();
  foreach (var entity in entities)
  {
      ThreadPool.QueueUserWorkItem(
          delegate
          {
              try
              {
                   ProcessEntity(entity);
              }
              catch (Exception)
              {
                  throw;
              }
          });
  }
  </code></pre>
  
  <p>I think it may have something to with passing an entity to a thread from the main thread as the error seems to throw as soon as I try and access a property of <code>entity</code>.</p>
  
  <p>Anyone have any idea's why this is happening and how I can resolve it?</p>
  
  <p><b>Update</b></p>
  
  <p>Here is what I decided to go with:</p>
  
  <pre><code>var events = new Dictionary&lt;int, AutoResetEvent&gt;();
  var repo = new Repository();
  var entities = repo.GetAllEntities();
  foreach (var entity in entities)
  {
      events.Add(entity.ID, new AutoResetEvent(false));
      ThreadPool.QueueUserWorkItem(
          delegate
          {
              var repo = new Repository();
              try
              {
                  ProcessHierarchy(repo.GetEntity(entity.ID), ReportRange.Weekly);
              }
              catch (Exception)
              {
                  throw;
              }
              finally
              {
                  events[entity.ID].Set();
              }
          });
  }
  
  WaitHandle.WaitAll(events.Values.ToArray());
  </code></pre>
  
  <p>Improvements/Suggestions welcome, but this seems to have done the trick.</p>