C#多线程通信
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace App.Test.Csharep.线程通信
{
public class MainThread
{
/// <summary>
/// 开始执行通知
/// </summary>
private EventWaitHandle dataChangeEvent = new AutoResetEvent(false); public int openDoorNum = ; /// <summary>
/// 测试流程: 完成10次开门后,每次开门完成都要完成进门操作,主线程完成开门,子线程完成进门
/// </summary>
public void Run()
{
var thread = new Thread(new ThreadStart(InputDoor));
thread.Name = "进门线程";
thread.IsBackground = true;
thread.Start(); Thread.Sleep(); for (int i = ; i < ; i++)
{
openDoorNum++;
Console.WriteLine("AA完成开门第" + openDoorNum + "次开门"); /// 通知已经完成开门操作
dataChangeEvent.Set(); /// 在执行dataChangeEvent.Set()后,dataChangeEvent.WaitOne()开始获取信号,为防止没有获取到信号时
/// 又执行dataChangeEvent.Set()方法,则上次的dataChangeEvent.WaitOne()需要执行的代码不会被执行,
/// 所以暂时休眠,否则进门可能次数不够
Thread.Sleep();
} Console.Read();
} /// <summary>
/// 完成进门操作
/// </summary>
private void InputDoor()
{
///收到开门的线程通知,WaitOne方法如果在通知线程set()前如果能及时收到信号,则一直会处于阻塞代码
/// 如果在dataChangeEvent.WaitOne()过程中获取信号同时,被调用线程给set()了,则dataChangeEvent.WaitOne()
/// 应该是收不到信号的,所以要在调用线程中执行完dataChangeEvent.set()后应该休眠一会,在调用dataChangeEvent.set() /// 保证子线程一直在处于运行状态
while (true)
{
//if (dataChangeEvent.WaitOne())
//{
// Console.WriteLine("\tA第" + openDoorNum + "次进门");
//} /// 等待100毫秒,没有收到信号则释放,继续往下面执行,date会被赋值
if (dataChangeEvent.WaitOne(, false))
{
Console.WriteLine("\t 【" + Thread.CurrentThread.Name + "】A第" + openDoorNum + "次进门");
}
}
}
}
}