关于ManualResetEven简单用法:
一、构造函数
// 摘要:
//用一个指示是否将初始状态设置为终止的布尔值初始化 System.Threading.ManualResetEvent 类的新实例。
// 参数:
// initialState:
// 如果为 true,则将初始状态设置为终止;如果为 false,则将初始状态设置为非终止。
public ManualResetEvent(bool initialState);
在实例化ManualResetEvent的时候需要传initialState(true/false)的值,如果传initialState的值为true
表示该ManualResetEvent的实例是终止状态,该ManualResetEvent是终止状态的情况下调用WaitOne方法的时候是不起作用;如果initialState的值为 false即非终止状态,当initialState为false的时候调用WaitOne方法才会有线程堵塞,效果如下图:
1.ManualResetEvent实例的时候参数为true调用WaitOne情况(调用WaitOne方法是不起作用没有堵塞线程效果)
class ThreadClass
{
public static ManualResetEvent mre = new ManualResetEvent(true);
public static void trmain()
{
Thread tr = Thread.CurrentThread;
Console.WriteLine("Thread: waiting for an event");
mre.WaitOne();
Console.WriteLine("Thread: got an event");
for (int x = 0; x < 10; x++)
{
Thread.Sleep(1000);
Console.WriteLine(tr.Name + ": " + x);
}
}
static void Main(string[] args)
{
Thread thrd1 = new Thread(new ThreadStart(trmain));
thrd1.Name = "Thread";
thrd1.Start();
for (int x = 0; x < 10; x++)
{
Thread.Sleep(900);
Console.WriteLine("Main:" + x);
//if (5 == x) mre.Set();
}
while (thrd1.IsAlive)
{
Thread.Sleep(1000);
Console.WriteLine("Main: waiting for thread to stop");
}
Console.ReadLine();
}
}
2.ManualResetEvent实例的时候参数为false调用WaitOne情况(调用WaitOne方法是作用堵塞线程效果)
class ThreadClass
{
public static ManualResetEvent mre = new ManualResetEvent(false);
public static void trmain()
{
Thread tr = Thread.CurrentThread;
Console.WriteLine("Thread: waiting for an event");
mre.WaitOne();
Console.WriteLine("Thread: got an event");
for (int x = 0; x < 10; x++)
{
Thread.Sleep(1000);
Console.WriteLine(tr.Name + ": " + x);
}
}
static void Main(string[] args)
{
Thread thrd1 = new Thread(new ThreadStart(trmain));
thrd1.Name = "Thread";
thrd1.Start();
for (int x = 0; x < 10; x++)
{
Thread.Sleep(900);
Console.WriteLine("Main:" + x);
//if (5 == x) mre.Set();
}
while (thrd1.IsAlive)
{
Thread.Sleep(1000);
Console.WriteLine("Main: waiting for thread to stop");
}
Console.ReadLine();
}
}
二、需要理解和掌握的几个方法
1.WaiOne
阻止当前线程,直到收到信号(当然初始化状态需要为false)
WaitOne有几个重载方法,通过时间进行WaitOne,如果超时就不阻塞了.
其他几个版本:MSDN地址
2.Set
将事件状态设置为终止状态,允许一个或多个等待线程继续。
3.ReSet
将事件状态设置为非终止状态,导致线程阻止。
本文介绍了System.Threading.ManualResetEvent类的使用方法,包括构造函数、WaitOne、Set和Reset等核心方法。通过示例对比了不同初始化状态下WaitOne方法的行为差异。
2355

被折叠的 条评论
为什么被折叠?



