using System;
using System.Threading;
namespace ThreadingTester
{
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);
if (x==5)
{
mre.Reset();
mre.WaitOne();
}
}
}
static void Main(string[] args)
{
Thread thrd1=new Thread(new ThreadStart(trmain));
thrd1.Name="thread1";
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");
mre.Set();
}
Console.ReadLine();
}
}
}
本文展示了一个使用C#编写的简单示例程序,通过ManualResetEvent来控制线程的暂停与继续。主线程与子线程间通过设置与等待事件来同步执行流程。
1138

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



