线程池如何等待所有线程执行结束

时间:2022-12-18 18:28:13

internal sealed class AClass
{
public int Method(int num)
{
Thread.Sleep(1000);
return num * num;

}
public void UsingCallback(int numToDo)
{
int[] squares = new int[numToDo];
AutoResetEvent done = new AutoResetEvent(false);

//在其他线程上执行任务
for(int n = 0; n < squares.Length; n++)
{
ThreadPool.QueueUserWorkItem(
obj => {
int num = (int)obj;
squares[num] = Method(num);

//最后一个任务,就让主线程继续运行
if(Interlocked.Decrement(ref numToDo) == 0)
{
done.Set();
}
},n);
}
//等待其他所有线程结束运行
done.WaitOne();

for(int n = 0; n < squares.Length; n++)
{
Console.WriteLine("Index{0},Square{1}", n, squares[n]);
}
}
}