有时候,我们创建了多线程,需要知道是否都完成了各自的工作。比如说,开启了多线程的下载,如何终止所有的线程并且在确保所有线程都终止之后才继续执行程序的退出呢?
1 public partial class MainWindow : Window 2 { 3 public MainWindow() 4 { 5 InitializeComponent(); 6 } 7 8 private volatile bool isContinue = false; 9 static List<WaitHandle> waitHandles = new List<WaitHandle>(); 10 11 private void Button_ThreadStart_Click(object sender, RoutedEventArgs e) 12 { 13 if (isContinue) 14 return; 15 16 isContinue = true; 17 18 Thread t = new Thread(TestWaitAll);//先开启一个线程 19 t.Name = "TestWaitAll"; 20 t.Start(); 21 } 22 23 private void Button_ThreadStop_Click(object sender, RoutedEventArgs e) 24 { 25 isContinue = false; 26 } 27 28 public void TestWaitAll() 29 { 30 for (int i = 0; i < 5; i++) 31 {
//WaitHandle是一个抽像类别所以得实体化它的子类,也就是 ManualResetEvent 类 或 AutoResetEvent 类 32 ManualResetEvent wh = new ManualResetEvent(false); 33 waitHandles.Add(wh); 34 ThreadPool.QueueUserWorkItem(Task, wh); 35 } 36 WaitHandle.WaitAll(waitHandles.ToArray()); 37 38 Console.WriteLine("所有线程都终止!!!!!!"); 39 MessageBox.Show("搞定!"); 40 } 41 42 public void Task(Object state) 43 { 44 ManualResetEvent mre = (ManualResetEvent)state; 45 while (isContinue) 46 { 47 Console.WriteLine("{0} : {1}", mre.Handle.ToString(), DateTime.Now.ToLongTimeString()); 48 Thread.Sleep(1000); 49 } 50 Console.WriteLine("当前线程终止"); 51 mre.Set(); 52 } 53 }
如果不开启线程而是直接在UI线程调用TestWaitAll(),就会有异常
WaitHandle.WaitAll(waitHandles),主线程乖乖等待所有线程完成工作
WaitHandle.WaitAll(waitHandles,2000),设定等待时间,表示主线程愿意等待子线程执行两秒钟
WaitHandle.WaitAny,就是等待任何一线程完成工作
参考:
Thread执行循环的顺序启动WaitHandle.WaitAll方法