.NET并行处理ArrayList

a_p*_*son 3 .net c# collections multithreading

我试图第一次嵌入多线程并遇到一些意想不到的问题,希望你能提供帮助.

这是给我带来麻烦的代码片段:

ArrayList recordsCollection = new ArrayList();
ArrayList batchCollection = null;
int idx = 0;

while(true)
{
  // Some code to generate and assign new batchCollection here
  recordsCollection.Add(batchCollection);

  ThreadPool.QueueUserWorkItem(delegate
  {
    ProcessCollection(recordsCollection.GetRange(idx, 1));
  });
  Interlocked.Increment(ref idx);
}

private void ProcessCollection(ArrayList collection)
{
   // Do some work on collection here
}
Run Code Online (Sandbox Code Playgroud)

一旦调用了Process Collection方法并且我试图遍历集合,我就会得到"底层列表中的范围无效".

提前致谢!

更新:伙计们,谢谢你们每一个人.通过应用您的建议,我能够大大简化并使其工作.

Mar*_*ers 5

你在Interlocked.Increment这里的使用是不必要的.您希望局部变量idx只能被一个线程看到,因此不需要锁定.

目前,您正在"关闭循环变量",这意味着线程会看到变量的最新值,而不是创建委托时的值.您希望其他线程接收此变量的副本.即使原始变量发生变化,这些副本也不会改变.

尝试将代码更改为:

int j = idx;
ThreadPool.QueueUserWorkItem(delegate
{
    ProcessCollection(recordsCollection.GetRange(j, 1));
});
Run Code Online (Sandbox Code Playgroud)

相关问题:

相关文章: