谈谈AutoResetEvent的用法

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事件对线程有中断的作用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值