我第一次尝试嵌入多线程并遇到了一些意外的问题,希望您能帮忙。
这是让我困扰的代码片段:
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
}
一旦调用Process Collection方法并尝试迭代集合时,我会收到“底层列表中的范围无效”的错误信息。
提前感谢!
更新:各位,非常感谢你们每一个人。通过应用你们的建议,我能够大大简化代码并使其正常工作。
List<T>
而非ArrayList
。 - Mark Byers