我在c#中使用线程池创建了一个简单的程序,同时我将线程号作为参数传递,但我得到了异常(运行时异常(第19行(:索引在数组的边界之外。(
using System;
using System.Threading;
using System.Linq;
public class Program
{
private const byte TotalNoOfThread=10;
private int[] arrThreadRowProcessed;
private bool[] arrThreadRowIsCompleted;
private void ResetThread()
{
arrThreadRowProcessed = new int[TotalNoOfThread];
arrThreadRowIsCompleted = new bool[TotalNoOfThread];
}
private void TuroverDayWise(int ThreadNo)
{
Console.WriteLine("From THread ="+ThreadNo);
arrThreadRowIsCompleted[ThreadNo] = true; //Geting error on this point Index value show 10 but how
}
public void TuroverDayWise()
{
ResetThread();
Console.WriteLine("Reset the Data..");
for (int i = 0; i < TotalNoOfThread; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(x=>TuroverDayWise(i)));
}
while (arrThreadRowIsCompleted.Any(p => !p))
{
Thread.Sleep(2000);
}
}
public static void Main()
{
Program obj= new Program();
obj.TuroverDayWise();
}
}
在此行中。。。
ThreadPool.QueueUserWorkItem(new WaitCallback(x=>TuroverDayWise(i)));
调用时使用的是i的当前值(在外部递增(,而不是该值。您可以尝试将i值保存在一个临时变量中,这应该有效:
for (int i = 0; i < TotalNoOfThread; i++)
{
int local = i;
ThreadPool.QueueUserWorkItem(new WaitCallback(x => TuroverDayWise(local)));
}