title: Multithreading Entity Framework: The connection was not closed. The connection's current state is connecting
body: <p>So I have a windows service process that performs a workflow process. The back end uses Repository and UnitofWork Pattern and Unity on top of Entity Framework with the entities class generated from the edmx. I won't go into a whole lot of detail as its not necessary but basically there are 5 steps that the workflow goes through. A particular process might be at any stage at any point in time (in order of course). Step one just generates data for step two, which validates the data via a long running process to another server. Then step there generates a pdf with that data. For each stage we spawn a timer, however it is configurable to allow more than one timer to be spawned for each stage. Therein lays the problem. When I add a processor to a particular stage, it the following error randomly:</p>
  
  <p>The connection was not closed. The connection's current state is connecting.</p>
  
  <p>Reading up on this it seems obvious that this is happening because the context is trying to access the same entity from two threads. But this is where it is kind of throwing me for a loop. All of the information I can find on this states that we should be using a instance context per thread. Which as far as I can tell I am doing (see the code below). I am not using singleton pattern or statics or anything so I am not really sure why this is happening or how to avoid it. I have posted the relevant bits of my code below for your review.</p>
  
  <p>The base repository:</p>
  
  <pre><code> public class BaseRepository
  {
      /// &lt;summary&gt;
      /// Initializes a repository and registers with a &lt;see cref="IUnitOfWork"/&gt;
      /// &lt;/summary&gt;
      /// &lt;param name="unitOfWork"&gt;&lt;/param&gt;
      public BaseRepository(IUnitOfWork unitOfWork)
      {
          if (unitOfWork == null) throw new ArgumentException("unitofWork");
          UnitOfWork = unitOfWork;
      }
  
  
      /// &lt;summary&gt;
      /// Returns a &lt;see cref="DbSet"/&gt; of entities.
      /// &lt;/summary&gt;
      /// &lt;typeparam name="TEntity"&gt;Entity type the dbset needs to return.&lt;/typeparam&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      protected virtual DbSet&lt;TEntity&gt; GetDbSet&lt;TEntity&gt;() where TEntity : class
      {
  
          return Context.Set&lt;TEntity&gt;();
      }
  
      /// &lt;summary&gt;
      /// Sets the state of an entity.
      /// &lt;/summary&gt;
      /// &lt;param name="entity"&gt;object to set state.&lt;/param&gt;
      /// &lt;param name="entityState"&gt;&lt;see cref="EntityState"/&gt;&lt;/param&gt;
      protected virtual void SetEntityState(object entity, EntityState entityState)
      {
          Context.Entry(entity).State = entityState;
      }
  
      /// &lt;summary&gt;
      /// Unit of work controlling this repository.       
      /// &lt;/summary&gt;
      protected IUnitOfWork UnitOfWork { get; set; }
  
      /// &lt;summary&gt;
      /// 
      /// &lt;/summary&gt;
      /// &lt;param name="entity"&gt;&lt;/param&gt;
      protected virtual void Attach(object entity)
      {
          if (Context.Entry(entity).State == EntityState.Detached)
              Context.Entry(entity).State = EntityState.Modified;
      }
  
      protected virtual void Detach(object entity)
      {
          Context.Entry(entity).State = EntityState.Detached;
      }
  
      /// &lt;summary&gt;
      /// Provides access to the ef context we are working with
      /// &lt;/summary&gt;
      internal StatementAutoEntities Context
      {
          get
          {                
              return (StatementAutoEntities)UnitOfWork;
          }
      }
  }
  </code></pre>
  
  <p>StatementAutoEntities is the autogenerated EF class.</p>
  
  <p>The repository implementation:</p>
  
  <pre><code>public class ProcessingQueueRepository : BaseRepository, IProcessingQueueRepository
  {
  
      /// &lt;summary&gt;
      /// Creates a new repository and associated with a &lt;see cref="IUnitOfWork"/&gt;
      /// &lt;/summary&gt;
      /// &lt;param name="unitOfWork"&gt;&lt;/param&gt;
      public ProcessingQueueRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
      {
      }
  
      /// &lt;summary&gt;
      /// Create a new &lt;see cref="ProcessingQueue"/&gt; entry in database
      /// &lt;/summary&gt;
      /// &lt;param name="Queue"&gt;
      ///     &lt;see cref="ProcessingQueue"/&gt;
      /// &lt;/param&gt;
      public void Create(ProcessingQueue Queue)
      {
          GetDbSet&lt;ProcessingQueue&gt;().Add(Queue);
          UnitOfWork.SaveChanges();
      }
  
      /// &lt;summary&gt;
      /// Updates a &lt;see cref="ProcessingQueue"/&gt; entry in database
      /// &lt;/summary&gt;
      /// &lt;param name="queue"&gt;
      ///     &lt;see cref="ProcessingQueue"/&gt;
      /// &lt;/param&gt;
      public void Update(ProcessingQueue queue)
      {
          //Attach(queue);
          UnitOfWork.SaveChanges();
      }
  
      /// &lt;summary&gt;
      /// Delete a &lt;see cref="ProcessingQueue"/&gt; entry in database
      /// &lt;/summary&gt;
      /// &lt;param name="Queue"&gt;
      ///     &lt;see cref="ProcessingQueue"/&gt;
      /// &lt;/param&gt;
      public void Delete(ProcessingQueue Queue)
      {
          GetDbSet&lt;ProcessingQueue&gt;().Remove(Queue);  
          UnitOfWork.SaveChanges();
      }
  
      /// &lt;summary&gt;
      /// Gets a &lt;see cref="ProcessingQueue"/&gt; by its unique Id
      /// &lt;/summary&gt;
      /// &lt;param name="id"&gt;&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public ProcessingQueue GetById(int id)
      {
          return (from e in Context.ProcessingQueue_SelectById(id) select e).FirstOrDefault();
      }
  
      /// &lt;summary&gt;
      /// Gets a list of &lt;see cref="ProcessingQueue"/&gt; entries by status
      /// &lt;/summary&gt;
      /// &lt;param name="status"&gt;&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public IList&lt;ProcessingQueue&gt; GetByStatus(int status)
      {
          return (from e in Context.ProcessingQueue_SelectByStatus(status) select e).ToList();
      }
  
      /// &lt;summary&gt;
      /// Gets a list of all &lt;see cref="ProcessingQueue"/&gt; entries
      /// &lt;/summary&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public IList&lt;ProcessingQueue&gt; GetAll()
      {
          return (from e in Context.ProcessingQueue_Select() select e).ToList();
      }
  
      /// &lt;summary&gt;
      /// Gets the next pending item id in the queue for a specific work        
      /// &lt;/summary&gt;
      /// &lt;param name="serverId"&gt;Unique id of the server that will process the item in the queue&lt;/param&gt;
      /// &lt;param name="workTypeId"&gt;type of &lt;see cref="WorkType"/&gt; we are looking for&lt;/param&gt;
      /// &lt;param name="operationId"&gt;if defined only operations of the type indicated are considered.&lt;/param&gt;
      /// &lt;returns&gt;Next pending item in the queue for the work type or null if no pending work is found&lt;/returns&gt;
      public int GetNextPendingItemId(int serverId, int workTypeId, int? operationId)
      {
          var id = Context.ProcessingQueue_GetNextPending(serverId, workTypeId,  operationId).SingleOrDefault();
          return id.HasValue ? id.Value : -1;
      }
  
      /// &lt;summary&gt;
      /// Returns a list of &lt;see cref="ProcessingQueueStatus_dto"/&gt;s objects with all
      /// active entries in the queue
      /// &lt;/summary&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public IList&lt;ProcessingQueueStatus_dto&gt; GetActiveStatusEntries()
      {
          return (from e in Context.ProcessingQueueStatus_Select() select e).ToList();
      }
      /// &lt;summary&gt;
      /// Bumps an entry to the front of the queue 
      /// &lt;/summary&gt;
      /// &lt;param name="processingQueueId"&gt;&lt;/param&gt;
      public void Bump(int processingQueueId)
      {
          Context.ProcessingQueue_Bump(processingQueueId);
      }
  }
  </code></pre>
  
  <p>We use Unity for dependency injection, some calling code for example:</p>
  
  <pre><code>#region Members
      private readonly IProcessingQueueRepository _queueRepository;       
      #endregion
  
      #region Constructors
      /// &lt;summary&gt;Initializes ProcessingQueue services with repositories&lt;/summary&gt;
      /// &lt;param name="queueRepository"&gt;&lt;see cref="IProcessingQueueRepository"/&gt;&lt;/param&gt;        
      public ProcessingQueueService(IProcessingQueueRepository queueRepository)
      {
          Check.Require(queueRepository != null, "processingQueueRepository is required");
          _queueRepository = queueRepository;
  
      }
      #endregion
  </code></pre>
  
  <p>The code in the windows service that kicks off the timers is as follows:</p>
  
  <pre><code>            _staWorkTypeConfigLock.EnterReadLock();
          foreach (var timer in from operation in (from o in _staWorkTypeConfig.WorkOperations where o.UseQueueForExecution &amp;&amp; o.AssignedProcessors &gt; 0 select o) 
                                let interval = operation.SpawnInternval &lt; 30 ? 30 : operation.SpawnInternval 
                                select new StaTimer
                              {
                                  Interval = _runImmediate ? 5000 : interval*1000,
                                  Operation = (ProcessingQueue.RequestedOperation) operation.OperationId
                              })
          {
              timer.Elapsed += ApxQueueProcessingOnElapsedInterval;
              timer.Enabled = true;
              Logger.DebugFormat("Queue processing for operations of type {0} will execute every {1} seconds", timer.Operation, timer.Interval/1000);                
          }
          _staWorkTypeConfigLock.ExitReadLock();
  </code></pre>
  
  <p>StaTimer is just a wrapper on timer adding operation type. ApxQueueProcessingOnElapsedInterval then bascially just assigns work to the process based on the operation.</p>
  
  <p>I will also add a bit of the ApxQueueProcessingOnElapsedInterval code where we are spawning tasks.</p>
  
  <pre><code>            _staTasksLock.EnterWriteLock();
          for (var x = 0; x &lt; tasksNeeded; x++)
          {
              var t = new Task(obj =&gt; ProcessStaQueue((QueueProcessConfig) obj),
                               CreateQueueProcessConfig(true, operation), _cancellationToken);
  
  
              _staTasks.Add(new Tuple&lt;ProcessingQueue.RequestedOperation, DateTime, Task&gt;(operation, DateTime.Now,t));
  
              t.Start();
              Thread.Sleep(300); //so there are less conflicts fighting for jobs in the queue table
          }
          _staTasksLock.ExitWriteLock();
  </code></pre>