线程同步 - 信号同步-AutoResetEvent(1)
cs
using System;
using System.Threading;
using System.Windows.Forms;
namespace WaitHandleSample
{
public partial class Form1 : Form
{
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
// 允许新线程访问主线程的控件
CheckForIllegalCrossThreadCalls = false;
}
private void btnStartAThread_Click(object sender, EventArgs e)
{
Thread twork = new Thread(() =>
{
label1.Text = "线程启动。。。" + Environment.NewLine;
label1.Text += "开始处理一下实际的工作" + Environment.NewLine;
// 省略工作代码
label1.Text += "我开始等待别的线程给我信号,才愿意继续下去" + Environment.NewLine;
autoResetEvent.WaitOne();
label1.Text += "我继续做了一些工作,然后结束了";
});
twork.IsBackground = true;
twork.Start();
}
private void btnSet_Click(object sender, EventArgs e)
{
// 给在 autoResetEvent 上等待的线程一个信号
autoResetEvent.Set();
}
}
}