做项目时有一个需求。用一个线程去执行耗时操作。另一个线程需要使用第一个线程的操作结果。所以第二个线程需要等待第一个线程的状态。我在网上找了下资源,自己也尝试下。发现AutoResetEvent 满足我这个需求。
主线程操作。
线程1 =>{ “耗时操作;”} => 特殊任务完成。触发条件。 => 线程1.set();
线程2 => {"线程2.WaitOne();需要等待线程的的结果"}; 线程2得到线程1的触发。开始执行。
下面介绍一下它的使用方法
AutoResetEvent 概念
1.AutoResetEvent(bool state)。构造函数。
false:无信号,子线程的WaitOne方法不会被自动调用。
true:有信号,子线程的WaitOne方法会被自动调用。
2.public bool Reset ():将事件状态设置为非终止状态,导致线程阻止;如果该操作成功,则返回true;否则,返回false。
3.public bool Set ():将事件状态设置为终止状态,允许一个或多个等待线程继续;如果该操作成功,则返回true;否则,返回false。
4.WaitOne方法: 当在派生类中重写时,阻止当前线程,直到当前的 WaitHandle 收到信号。
以上是官方给的解释。
通过一个案例来加强一下。
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AutoEventTest
{
class Program
{
static AutoResetEvent autoReset = new AutoResetEvent(false);
static int num2 = 0;
static int num1 = 0;
static void Main(string[] args)
{
Console.WriteLine("Work method gignaled.\nMain starting.");
Console.WriteLine("Main ending.");
Task.Run(() =>
{
Console.WriteLine("Task2 Waiting...");
autoReset.WaitOne();
Console.WriteLine("Task2 begining...");
while (num1 < 3)
{
Console.WriteLine("task2 num = {0}",+ num1);
Thread.Sleep(1000);
num1++;
}
});
Task.Run(() =>
{
Console.WriteLine("Task1 Beginning...");
while (num2 < 3)
{
Console.WriteLine("task1 num = {0}",num2);
Thread.Sleep(1000);
num2++;
}
Console.WriteLine("task1 complete");
autoReset.Set();
});
Console.ReadLine();
}
}
}
task1先执行,task2开始等待(autoReset.WaitOne())。task1执行完毕后给task2发信号(autoReset.Set())。task1开始执行。以下是输入结果: