例子描述:人生都有追求幸福理想,下面就用三條線程得到房子,車子,妻子,等待全部得到後,顯示人生圓滿。
View Code using System; using System.Collections.Generic; using System.Windows.Forms; namespace WindowsApplication1 { static class Program { /// <summary> /// 應用程序的主入口點。 /// </summary> [MTAThread] //不支持一個 STA 線程上針對多個句柄的 WaitAll。解決辦法把STAThread改成MTAThread static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
View Code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //定義一個人對象 Person person = new Person(); //這個人去幹三件大事 Thread GetCarThread = new Thread(new ThreadStart(person.GetCar)); GetCarThread.Start(); Thread GetHouseThead = new Thread(new ThreadStart(person.GetHouse)); GetHouseThead.Start(); Thread GetWillThead = new Thread(new ThreadStart(person.GetWife)); GetWillThead.Start(); //等待三件事都幹成的喜訊通知信息 AutoResetEvent.WaitAll(person.autoEvents); //這個人就開心了。 person.ShowHappy(); } } public class Person { //建立事件數組 public AutoResetEvent[] autoEvents = null; public Person() { autoEvents = new AutoResetEvent[] { new AutoResetEvent(false), new AutoResetEvent(false), new AutoResetEvent(false) }; } public void GetCar() { MessageBox.Show("撿到奔馳"); autoEvents[0].Set(); } public void GetHouse() { MessageBox.Show("賺到房子"); autoEvents[1].Set(); } public void GetWife() { MessageBox.Show("騙到老婆"); autoEvents[2].Set(); } public void ShowHappy() { MessageBox.Show("人生要有的都有了,好開心"); } } }
注意:
AutoResetEvent.WaitAll();//AutoResetEvent繼承WaitHandle 等同於:WaitHandle.WaitAll();
WaitHandles 的數目必須少於或等於 64 個。