I am creating an application that requires me to use a DataContext inside threads. My application continues to throw an InvalidOperationException , similar to:
There is already an open DataReader associated with this Command which must be closed first
ExecuteReader requires an open and available Connection. The connection current state is connecting
These exceptions are intermittent.
Here is a snippet of my code:
var repo = new Repository(); var entities = repo.GetAllEntities(); foreach (var entity in entities) { ThreadPool.QueueUserWorkItem( delegate { try { ProcessEntity(entity); } catch (Exception) { throw; } }); }
I think this might have something to do with passing the entity to the stream from the main thread, as the error seems to throw as soon as I try to access the entity property.
Can anyone understand why this is happening and how can I solve it?
Update
Here is what I decided to go with:
var events = new Dictionary<int, AutoResetEvent>(); 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());
Improvements / Suggestions are welcome, but this seems to have done the trick.
multithreading c # linq-to-sql datacontext
James
source share