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()方法。
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秒。
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秒。