版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sss_369/article/details/86555890
public AutoResetEvent eventStop { get; set; }
AutoResetEvent多用于.Net多线程编程中。
当某个线程调用WaitOne方法后,信号处于发送状态,该线程会得到信号, 程序就会继续向下执行,否则就等待;
而且 AutoResetEvent.WaitOne()每次只允许一个线程进入,当某个线程得到信号后,
AutoResetEvent会自动又将信号设置为不发送状态,其他调用WaitOne的线程只有继续等待.也就是说,AutoResetEvent一次只唤醒一个线程,其他线程还是堵塞。
AutoResetEvent(bool initialState):用一个指示是否将初始状态设置为终止的布尔值初始化该类的新实例。
false:无信号,子线程的WaitOne方法不会被自动调用
true:有信号,子线程的WaitOne方法会被自动调用
Reset ():将事件状态设置为非终止状态,导致线程阻止;如果该操作成功,则返回true;否则,返回false。
Set ():将事件状态设置为终止状态,允许一个或多个等待线程继续;如果该操作成功,则返回true;否则,返回false。
WaitOne(): 阻止当前线程,直到收到信号。
WaitOne(TimeSpan, Boolean) :阻止当前线程,直到当前实例收到信号,使用 TimeSpan 度量时间间隔并指定是否在等待之前退出同步域。
WaitAll():等待全部信号。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace sss
{
class Program
{
static void Main()
{
Request req = new Request();//类
//这个人去干三件大事
Thread GetCarThread = new Thread(new ThreadStart(req.InterfaceA));
GetCarThread.Start();
Thread GetHouseThead = new Thread(new ThreadStart(req.InterfaceB));
GetHouseThead.Start();
//等待三件事都干成的喜讯通知信息
AutoResetEvent.WaitAll(req.autoEvents);
//这个人就开心了。
req.InterfaceC();
System.Console.ReadKey();
}
}
public class Request
{
//建立事件数组
public AutoResetEvent[] autoEvents = null;
public Request() //constructor
{
autoEvents = new AutoResetEvent[]
{
new AutoResetEvent(false),
new AutoResetEvent(false)
};
}
public void InterfaceA()
{
System.Console.WriteLine("请求A接口");
Thread.Sleep(1000 * 2);
autoEvents[0].Set();
System.Console.WriteLine("A接口完成");
}
public void InterfaceB()
{
System.Console.WriteLine("请求B接口");
Thread.Sleep(1000 * 1);
autoEvents[1].Set();
System.Console.WriteLine("B接口完成");
}
public void InterfaceC()
{
System.Console.WriteLine("两个接口都已经请求完,正在处理C");
}
}
}
【注】WaitOne 或WaitAll 最好都加上超时时间。否则没有收到信号,线程一直会阻塞。
参考文章
1. https://www.cnblogs.com/zhangweizhong/p/6628442.html