通过set和waitOne来控制子线程的运行和停止

时间:2023-12-20 18:51:44
  public partial class Form1 : Form
{ //自动重置事件类
//主要用到其两个方法 WaitOne() 和 Set() , 前者阻塞当前线程,后者通知阻塞线程继续往下执行
AutoResetEvent autoEvent = new AutoResetEvent(false); public Form1()
{
InitializeComponent();
}
public static bool _stop=true;
private void button3_Click(object sender, EventArgs e)
{
int i = ;
Thread NewThread = new Thread(Run);
NewThread.Start(i);
}
private void Run(object i)
{
Control.CheckForIllegalCrossThreadCalls = false;
int j = (int)i; while (true)
{
j++;
Thread.Sleep();
label1.Text = j.ToString();
label1.Refresh();
if(_stop)
autoEvent.WaitOne(); //阻塞当前线程,等待通知以继续执行
} } private void button1_Click(object sender, EventArgs e)
{
autoEvent.Set(); //通知阻塞的线程继续执行
_stop = false;
} private void button2_Click(object sender, EventArgs e)
{
_stop = true;
}
}

通过set和waitOne来控制子线程的运行和停止