我正在构建一个应用程序,它要求我使用DataContext的内部线程.我的应用程序不断抛出InvalidOperationException类似于:
There is already an open DataReader associated with this Command which must be closed first
ExecuteReader requires an open and available Connection. The connection's current state is connecting
这些例外是间歇性的.
这是我的代码片段:
var repo = new Repository();
var entities = repo.GetAllEntities();
foreach (var entity in entities)
{
ThreadPool.QueueUserWorkItem(
delegate
{
try
{
ProcessEntity(entity);
}
catch (Exception)
{
throw;
}
});
}
Run Code Online (Sandbox Code Playgroud)
我认为将一个实体传递给主线程中的一个线程可能会有一些问题,因为一旦我尝试访问一个属性,错误似乎就会抛出entity.
任何人都知道为什么会发生这种情况以及如何解决它?
更新
这是我决定采用的:
var events = new Dictionary<int, AutoResetEvent>();
var repo = new Repository();
var …Run Code Online (Sandbox Code Playgroud)