ArrayList的.NET并行​​处理 [英] .NET parallel processing of ArrayList

查看:155
本文介绍了ArrayList的.NET并行​​处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在嵌入多线程的第一次运行到一些意想不到的问题,希望能帮到你。

I am attempting at embedding multi-threading for the first time ever and running into some unexpected issues, hope you can help.

这里的code片段,让我的烦恼:

Here's the code fragment that gives me troubles:

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
}

在过程收集方法被调用,我试图遍历集合我得到基础列表中的范围是无效的。

Once the Process Collection method is invoked and I am attempting to iterate through collection I am getting "The range in the underlying list is invalid".

在此先感谢!

更新:伙计们,谢谢你们每一个人。通过将你的建议,我是能够大大简化,并得到它的工作。

Update: Guys, thank you to each and every one of you. Through applying your suggestions I was able to greatly simplify and get it to work.

推荐答案

您有几个问题。

  • 在像马克指出,你在拍摄这将真的在这里混淆事物的循环变量。
  • 您正在修改的集合,而在同一时间阅读它,而无需使用同步机制。

我假设你已经省略了code,用于获取 batchCollection ,然后定期从删除它们 recordsCollection 为简便起见,否则就不会有问题有作为。

I am assuming you have omitted the code for acquiring a batchCollection and then periodically removing them from recordsCollection for brevity, otherwise there would be issues there as well.

下面是如何修复它。

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

while(true)  
{  
  lock (recordsCollection) 
  {
    recordsCollection.Add(batchCollection);  
  }

  int capturedIndex = idx; // Used for proper capturing.

  ThreadPool.QueueUserWorkItem(delegate  
  {
    ArrayList range;
    lock (recordsCollection)
    {
      range = recordsCollection.GetRange(capturedIndex, 1);
    }
    ProcessCollection(range);  
  });  

  idx++;
}  

还是我重构版本里面,尽我所能告诉反正,做同样的事情...

Or my refactored version which, as best I can tell anyway, does the exact same thing...

List<List<Record>> recordsCollection = new ArrayList();  
List<Record> batchCollection = null;  

while(true)  
{  
  recordsCollection.Add(batchCollection);

  List<List<Record>> range = new List<List<Record>>();
  range.Add(batchCollection);

  ThreadPool.QueueUserWorkItem(delegate  
  {
    ProcessCollection(range);  
  });      
}  

这篇关于ArrayList的.NET并行​​处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆