原文:点击打开链接
1. MREDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ManualResetEventDemo
{
class MREDemo
{
private ManualResetEvent _mre;
public MREDemo()
{
this._mre = new ManualResetEvent(true);
}
public void CreateThreads()
{
Thread t1 = new Thread(new ThreadStart(Run));
t1.Start();
Thread t2 = new Thread(new ThreadStart(Run));
t2.Start();
}
public void Set()
{
this._mre.Set();
}
public void Reset()
{
this._mre.Reset();
}
private void Run()
{
string strThreadID = string.Empty;
try
{
while (true)
{
// 阻塞当前线程
this._mre.WaitOne();
strThreadID = Thread.CurrentThread.ManagedThreadId.ToString();
Console.WriteLine("Thread(" + strThreadID + ") is running...");
Thread.Sleep(5000);
}
}
catch (Exception ex)
{
Console.WriteLine("线程(" + strThreadID + ")发生异常!错误描述:" + ex.Message.ToString());
}
}
}
}
2. Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ManualResetEventDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("****************************");
Console.WriteLine("输入\"stop\"停止线程运行...");
Console.WriteLine("输入\"run\"开启线程运行...");
Console.WriteLine("****************************\r\n");
MREDemo objMRE = new MREDemo();
objMRE.CreateThreads();
while (true)
{
string input = Console.ReadLine();
if (input.Trim().ToLower() == "stop")
{
Console.WriteLine("线程已停止运行...");
objMRE.Reset();
}
else if (input.Trim().ToLower() == "run")
{
Console.WriteLine("线程开启运行...");
objMRE.Set();
}
}
}
}
}