如果子线程数量有限,可以使用WaitHandle里的 WaitHandle.WaitAll()方法进行处理,但该WaitHandle 最大支持64个线程处理。
实例代码如下:(参照MSDN)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace AppTest
{
public class ThreadPoolDemo
{
public static readonly ThreadPoolDemo Instance = new ThreadPoolDemo();
Random r = new Random();
/// <summary>
/// 主线程等待所有子线程执行完毕demo
/// </summary>
public void MainThreadWaitAllSonThreadFinshed()
{
WaitHandle[] waitHandles = new WaitHandle[]{
new AutoResetEvent(false),
new AutoResetEvent(false)
};
// Queue up two tasks on two different threads;
// wait until all tasks are completed.
DateTime dt = DateTime.Now;
Console.WriteLine("Main thread is waiting for BOTH tasks to complete.");
ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
//等待所有线程执行完毕
WaitHandle.WaitAll(waitHandles);
// The time shown below should match the longest task.
Console.WriteLine("Both tasks are completed (time waited={0})",
(DateTime.Now - dt).TotalMilliseconds);
// Queue up two tasks on two different threads;
// wait until any tasks are completed.
dt = DateTime.Now;
Console.WriteLine();
Console.WriteLine("The main thread is waiting for either task to complete.");
ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask), waitHandles[1]);
//等待任一个线程执行完毕
int index = WaitHandle.WaitAny(waitHandles);
// The time shown below should match the shortest task.
Console.WriteLine("Task {0} finished first (time waited={1}).",
index + 1, (DateTime.Now - dt).TotalMilliseconds);
}
/// <summary>
/// 执行的工作任务
/// </summary>
public void DoTask(object state)
{
AutoResetEvent are = (AutoResetEvent)state;
int time = 1000 * r.Next(2, 10);
Console.WriteLine("Performing a task for {0} milliseconds.", time);
Thread.Sleep(time);
are.Set();
}
}