c# AutoResetEvent

前言

在异步中如何控制两个线程这样运动呢,在A线程执行到某个位置的时候等待B线程执行,然后B运行到某个位置有又开始运行A,这时候可以用AutoResetEvent。

正文

代码:

private static AutoResetEvent _workerEvent = new AutoResetEvent(false);
private static AutoResetEvent _mainEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
	var t = new Thread(() => Process(10));
	t.Start();
	Console.WriteLine("start process sign!");
	_workerEvent.WaitOne();
	Thread.Sleep(TimeSpan.FromSeconds(5));
	_mainEvent.Set();
	Console.WriteLine("_workerEvent ");
	_workerEvent.WaitOne();
}

static void Process(int seconds)
{
	Console.WriteLine("Starting a long running work....");
	Thread.Sleep(TimeSpan.FromSeconds(2));
	Console.WriteLine("Work is done");
	_workerEvent.Set();
	Console.WriteLine("Waiting for a main thread to complete its work");
	_mainEvent.WaitOne();
	Console.WriteLine("Starting second operation....");
	Console.WriteLine("Work is done!");
	Console.WriteLine("_workerEvent release ");
	_workerEvent.Set();
}

这个可以自己跑一遍。

后续

原理后续补齐。

原文地址:https://www.cnblogs.com/aoximin/p/13220093.html