ManualResetEvent为多个线程之间提供了一个共享的信号。
初始化:ManualResetEvent mre=new ManualResetEvent(true)
初始值为true表示有信号,为false表示无信号
使用:mre.Set()将有信号的消息通知到各线程
mre.Reset()将无信号的消息通知到各线程
线程内使用是通过mre.WaitOne()来进行获取信号的:
有信号时(Set,或true)线程中此语句之后的代码可以继续执行;
无信号时(Reset,或false)线程中此语句之后的代码将被阻塞。
我做了一个实例,用来演示ManualResetEvent的用法。
主界面有四个进度条,表示四台机器,其中三台电动机,一台柴油机;
设置了一个ManualResetEvent信号,表示power电力,有电时,电动机才能
运转,柴油机则不受power信号的影响。
初始时,power有信号,点击START按钮,四台机器一起运转,
当点击关闭电源时,所有电动机停止,柴油机继续运转
当点击接通电源时,电动机和柴油机都会运行了!
PS:三台电动机特意设置了不同速度。
public partial class Form1 : Form { ManualResetEvent power = new ManualResetEvent(true); Thread tDieselEngine; Thread tElectricMotor1, tElectricMotor2, tElectricMotor3; public Form1() { InitializeComponent(); //electric motor progressBar1.Minimum = 0; progressBar1.Maximum = 100; progressBar1.Value = 0; progressBar1.Tag = 500;//周期 //electric motor progressBar2.Minimum = 0; progressBar2.Maximum = 100; progressBar2.Value = 0; progressBar2.Tag = 200;//周期 //diesel engine progressBar3.Minimum = 0; progressBar3.Maximum = 100; progressBar3.Value = 0; //electric motor progressBar4.Minimum = 0; progressBar4.Maximum = 100; progressBar4.Value = 0; progressBar4.Tag = 100;//周期 tDieselEngine =new Thread(DieselEngineFun); tElectricMotor1 = new Thread(new ParameterizedThreadStart(ElectricMotorFun)); tElectricMotor2 = new Thread(new ParameterizedThreadStart(ElectricMotorFun)); tElectricMotor3 = new Thread(new ParameterizedThreadStart(ElectricMotorFun)); } void DieselEngineFun() { while (true) { //power.WaitOne(); Invoke(new Action<ProgressBar>((pb) => pb.Value = (pb.Value + 1) % pb.Maximum), progressBar3); Thread.Sleep(1000); } } void ElectricMotorFun(object opb) { ProgressBar epb = opb as ProgressBar; int rate = (int)epb.Tag; while (true) { power.WaitOne();//会在此等待电源 Invoke(new Action<ProgressBar>((pb) => pb.Value = (pb.Value + 1) % pb.Maximum), epb); Thread.Sleep(rate); } } private void btnStart_Click(object sender, EventArgs e) { tDieselEngine.Start(); tElectricMotor1.Start(progressBar1); tElectricMotor2.Start(progressBar2); tElectricMotor3.Start(progressBar4); } private void btnReset_Click(object sender, EventArgs e) { power.Reset(); } private void btnSet_Click(object sender, EventArgs e) { power.Set(); } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { tDieselEngine.Abort(); tElectricMotor1.Abort(); tElectricMotor2.Abort(); tElectricMotor3.Abort(); } }