这是正常的循环捕获问题 - 你已经捕获了循环变量,所以在线程实际启动的时候,i
是最终值,这是数组中的无效索引。该解决方案是创建一个新的变量内的循环,捕获,与其:
Thread[] threads = new Thread[threadData.Length];
for (int i = 0; i < threadData.Length; i++)
{
int copy = i;
threads[i]= new System.Threading.Thread(() => threadWork(threadData[copy]));
threads[i].Start();
}
你可以阅读更多有关这对埃里克利珀的博客:part 1; part 2。
就个人而言,我会考虑使用更多的List<T>
,并尽可能使用foreach
甚至LINQ。诚然,foreach
不会解决这个问题,但它通常会更清洁IMO。
这里有一个如何在LINQ已经做了一个例子:
List<Thread> threads = threadData.Select(x => new Thread(() => ThreadWork(x)))
.ToList();
foreach (Thread thread in threads)
{
thread.Start();
}
还是采用了直板foreach循环,从每一个线程,当您去:
List<Thread> threads = new List<Thread>();
foreach (var data in threadData)
{
var dataCopy = data;
Thread thread = new Thread(() => ThreadWork(dataCopy));
thread.Start();
threads.Add(thread);
}
感谢乔恩,我为那个先回答的人标记了正确的答案。 – deadlock 2011-01-24 20:54:42