Example Description: Life has the ideal of pursuing happiness. Next we will use three threads to get a house, a car, and a wife. After all, we will see that life is complete.
View Code
Using System;
Using System. Collections. Generic;
Using System. Windows. Forms;
Namespace WindowsApplication1
{
Static class Program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[MTAThread] // does not support WaitAll for multiple handles on a single STA thread. Solution: Change STAThread to 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 button#click (object sender, EventArgs e)
{
// Define a person object
Person person = new Person ();
// This person will do three things
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 ();
// Wait for the successful notifications
AutoResetEvent. WaitAll (person. autoEvents );
// This person will be happy.
Person. ShowHappy ();
}
}
Public class Person
{
// Create an event Array
Public AutoResetEvent [] autoEvents = null;
Public Person ()
{
AutoEvents = new AutoResetEvent []
{
New AutoResetEvent (false ),
New AutoResetEvent (false ),
New AutoResetEvent (false)
};
}
Public void GetCar ()
{
MessageBox. Show ("pick up Mercedes-Benz ");
AutoEvents [0]. Set ();
}
Public void GetHouse ()
{
MessageBox. Show ("House earning ");
AutoEvents [1]. Set ();
}
Public void GetWife ()
{
MessageBox. Show ("cheat wife ");
AutoEvents [2]. Set ();
}
Public void ShowHappy ()
{
MessageBox. Show ("You have to have everything in your life, so happy ");
}
}
}
Note:
AutoResetEvent. WaitAll (); // AutoResetEvent inherits the WaitHandle equivalent to: WaitHandle. WaitAll ();
The number of WaitHandles must be less than or equal to 64.