线程之间的通信是通过发信号来进行沟通的。、
ManualResetEvent发送Set信后后,需要手动Reset恢复初始状态。而对于AutoResetEvent来说,当发送完毕Set信号后,会自动Reset。
代码差别:
ManualResetEvent
class ThreadClass { public static ManualResetEvent Manual1 = new ManualResetEvent(false); public static ManualResetEvent Manual2 = new ManualResetEvent(false); //手动Reset static bool m_Err = false; static List<string> lists; static int iNum = 0; static void Main(string[] args) { lists = new List<string>(); Thread thrd1 = new Thread(new ThreadStart(MethodSecond)); thrd1.Name = "thread Second"; thrd1.Start(); Thread thrd12 = new Thread(() => { MethodFirst(); }); thrd12.Name = "thread First"; thrd12.Start(); } private static void MethodFirst() { while (true) { Console.WriteLine("加 开始" + iNum.ToString()); Thread.Sleep(1000); try { for (int x = 0; x < iNum; x++) { lists.Add(x.ToString()); Console.WriteLine("加:" + x.ToString()); } } catch { Console.WriteLine("错误"); m_Err = true; } Manual2.Set(); Manual2.Reset();//手工Reset if (m_Err) { Manual2.Set(); break; } Manual1.WaitOne(); } } public static void MethodSecond() { Thread tr = Thread.CurrentThread; while (true) { iNum++; Console.WriteLine("减 等待"); Manual2.WaitOne(); Thread.Sleep(1000); try { if (lists.Count > 0) { jian(); } } catch { Console.WriteLine("错误"); m_Err = true; } Manual1.Set(); Manual1.Reset(); //手工Rest if (m_Err) { Manual1.Set(); break; } } } private static void jian() { Thread.Sleep(1000); Console.WriteLine("减" + lists[0]); lists.RemoveAt(0); if (lists.Count > 0) { jian(); } } }
AutoResetEvent
class Program { public static AutoResetEvent Auto1 = new AutoResetEvent(false); public static AutoResetEvent Auto2 = new AutoResetEvent(false); static bool m_Err = false; static List<string> lists; static int iNum = 0; static void Main(string[] args) { lists = new List<string>(); Thread thrd1 = new Thread(new ThreadStart(MethodSecond)); thrd1.Name = "thread Second"; thrd1.Start(); Thread thrd12 = new Thread(() => { MethodFirst(); }); thrd12.Name = "thread First"; thrd12.Start(); } private static void MethodFirst() { while (true) { Console.WriteLine(); Console.WriteLine("加 开始" + iNum.ToString()); Thread.Sleep(1000); try { for (int x = 0; x < iNum; x++) { lists.Add(x.ToString()); Console.WriteLine("加:" + x.ToString()); } } catch { Console.WriteLine("错误"); m_Err = true; } Auto2.Set(); //Manual2.Reset(); 无需Reset if (m_Err) { Auto2.Set(); break; } Auto1.WaitOne(); } } public static void MethodSecond() { Thread tr = Thread.CurrentThread; while (true) { iNum++; Console.WriteLine("减 等待"); Auto2.WaitOne(); Thread.Sleep(1000); try { if (lists.Count > 0) { jian(); } } catch { Console.WriteLine("错误"); m_Err = true; } Auto1.Set(); // Manual1.Reset(); //无需Reset if (m_Err) { Auto1.Set(); break; } } } private static void jian() { Thread.Sleep(1000); Console.WriteLine("减" + lists[0]); lists.RemoveAt(0); if (lists.Count > 0) { jian(); } } }