线程同步 - 信号同步-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();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39