C#多线程通信
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.Threading.Tasks; 7 8 namespace App.Test.Csharep.线程通信 9 { 10 public class MainThread 11 { 12 /// <summary> 13 /// 开始执行通知 14 /// </summary> 15 private EventWaitHandle dataChangeEvent = new AutoResetEvent(false); 16 17 18 public int openDoorNum = 0; 19 20 /// <summary> 21 /// 测试流程: 完成10次开门后,每次开门完成都要完成进门操作,主线程完成开门,子线程完成进门 22 /// </summary> 23 public void Run() 24 { 25 var thread = new Thread(new ThreadStart(InputDoor)); 26 thread.Name = "进门线程"; 27 thread.IsBackground = true; 28 thread.Start(); 29 30 Thread.Sleep(500); 31 32 for (int i = 0; i < 10; i++) 33 { 34 openDoorNum++; 35 Console.WriteLine("AA完成开门第" + openDoorNum + "次开门"); 36 37 /// 通知已经完成开门操作 38 dataChangeEvent.Set(); 39 40 /// 在执行dataChangeEvent.Set()后,dataChangeEvent.WaitOne()开始获取信号,为防止没有获取到信号时 41 /// 又执行dataChangeEvent.Set()方法,则上次的dataChangeEvent.WaitOne()需要执行的代码不会被执行, 42 /// 所以暂时休眠,否则进门可能次数不够 43 Thread.Sleep(1); 44 } 45 46 Console.Read(); 47 } 48 49 /// <summary> 50 /// 完成进门操作 51 /// </summary> 52 private void InputDoor() 53 { 54 ///收到开门的线程通知,WaitOne方法如果在通知线程set()前如果能及时收到信号,则一直会处于阻塞代码 55 /// 如果在dataChangeEvent.WaitOne()过程中获取信号同时,被调用线程给set()了,则dataChangeEvent.WaitOne() 56 /// 应该是收不到信号的,所以要在调用线程中执行完dataChangeEvent.set()后应该休眠一会,在调用dataChangeEvent.set() 57 58 /// 保证子线程一直在处于运行状态 59 while (true) 60 { 61 //if (dataChangeEvent.WaitOne()) 62 //{ 63 // Console.WriteLine(" A第" + openDoorNum + "次进门"); 64 //} 65 66 /// 等待100毫秒,没有收到信号则释放,继续往下面执行,date会被赋值 67 if (dataChangeEvent.WaitOne(100, false)) 68 { 69 Console.WriteLine(" 【" + Thread.CurrentThread.Name + "】A第" + openDoorNum + "次进门"); 70 } 71 } 72 } 73 } 74 }