AutoResetEvent属性介绍
构造函数:AutoResetEvent(bool initialState),声明时需要指明initialState值。
false:无信号,子线程的WaitOne方法不会被自动调用
true:有信号,子线程的WaitOne方法会被自动调用
Reset():将事件状态设置为非终止状态,导致线程阻止;如果该操作成功,则返回true;否则,返回false。
Set ():将事件状态设置为终止状态,允许一个或多个等待线程继续;如果该操作成功,则返回true;否则,返回false。
WaitOne(): 阻止当前线程,直到收到信号。
WaitOne(TimeSpan, Boolean) :阻止当前线程,直到当前实例收到信号,使用 TimeSpan 度量时间间隔并指定是否在等待之前退出同步域。
WaitAll():等待全部信号
实例介绍
在这里插入代码片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 :Form
{
AutoResetEvent Autoevent1 = new AutoResetEvent( false );//AutoResetEvent声明
AutoResetEvent Autoevent2 = new AutoResetEvent( false );
private int k,i,j; ///计时,可以借此查看AutoResetEvent发出信息的时机
private delegate void FlushClient( ); //委托代理跨线程操作控件
public Form1( )
{
InitializeComponent( );
//timer从界面拖拉,timer1间隔100,timer2间隔为500,timer3间隔为1000
}
private void button1_Click( object sender, EventArgs e )
{
timer1.Enabled = true;
timer2.Enabled = true;
timer3.Enabled = true; /启动三个计时
Thread t1 = new Thread( dowork );
t1.Start( );
}
private void dowork( )
{
int m = 1;
while(m == 1)
{ //多次循环,查看AutoResetEvent的set属性和waitOne之间的配合
Autoevent1.WaitOne( );
juice( ); 跨线程操作控件显示set启动时机
}
}
private void juice( )
{
if(textBox6.InvokeRequired)
{
FlushClient fc = new FlushClient( juice);
this.Invoke( fc );
}
else
{
textBox6.Text =k.ToString();
textBox5.Text = i.ToString( );
}
}
private void timer1_Tick( object sender, EventArgs e )
{
k++;
textBox1.Text = (k).ToString( );
}
private void timer2_Tick( object sender, EventArgs e )
{
i++;
textBox2.Text =(i).ToString();
Autoevent1.Set( );阻塞线程继续运行
}
private void timer3_Tick( object sender, EventArgs e )
{
j++;
textBox3.Text = (j).ToString( );
}
}
}
个人心得:
计划借助AutoResetEvent来实现对线程的暂停和重启,通过这个例子,可以看到AutoResetEvent事件对线程有中断的作用。