ManualResetEvent类的用法

ManualResetEvent对象只能拥有两种状态之一:有信号(True)或无信号(false)。
ManualResetEvent类继承于WaitHandle类,其构造函数的参数可确定对象的初始状态。
Set()和Reset()方法返回一个布尔值,表示是否进行了成功的修改。
为了把状态修改为有信号的,必须调用Set()方法。
为了把状态修改为无信号的,必须调用ReSet()方法。
WaitOnly()方法使用 32 位有符号整数度量时间间隔并指定是否在等待之前退出同步域,以此阻止当前线程,直到当前的 WaitHandle 收到信号。



public   class  ClassForMain
{
    
public class NonSignaledManual
    
{



        
public static void Main(string[] args)
        
{
            ManualResetEvent mansig;
            mansig 
= new ManualResetEvent(false);
            Console.WriteLine(
"ManualResetEvent Before WaitOne");
            
bool b = mansig.WaitOne(1000,true);
            Console.WriteLine(
"ManualResetEvent After WaitOne" + b);
        }

    }


}

   上面的例子中,构造了false值的ManualResetEvent对象,布尔值False把ManualResetEvent对象的初始状态设置为无信号。接着调用基类WaigHandle的WaitOne()方法。
程序块在WaitOne()方法中暂停一秒,然后因为超时而退出。ManualResetEvent的状态仍然是False,因而WaitOne()返回的布尔值b是False。


下面的例子把有信号改为无信号,调用ReSet()方法。
using System;
using System.Threading;
using System.Runtime.CompilerServices;



public class ClassForMain
{
    public class NonSignaledManual
    {
        public static void Main(string[] args)
       {
            ManualResetEvent mansig;
            mansig = new ManualResetEvent(true);
          
            bool state = mansig.WaitOne(1000,true); 
            Console.WriteLine("ManualResetEvent After WaitOne" + state);
            mansig.Reset();
             state = mansig.WaitOne(1000, true); 
            Console.WriteLine("ManualResetEvent After WaitOne" + state );
        }
    }

}
     在ManualReset中,MnualTResetEvent对象的构造函数将其状态设置为有信号(true),结果,线程不在第一个WaitOne()方法中等待,并返回True值。接着,ManualResetEvent对象的状态重新设置为无信号的(false),于是线程在超时之前必须等待5秒。











 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值