|
但问题是你不知道花什么时候才送到MM的手里,打早了打迟了都不好,这时你可以使用ManualResetEvent对象帮忙。当委托小伙子送花过去的时候,使用ManualResetEvent的WaitOne方法进行等待。当小伙子把花送到MM的手中时,再调用一下ManualResetEvent的Set方法,你就可以准时地打电话过去了。 另外ManualResetEvent还有一个Reset方法,用来重新阻断调用者执行的,情况就好比你委托了这个小伙子送花给N个MM, 而又想准时地给这N个MM打电话的情况一样。 using System; using System.Threading; public class TestMain { private static ManualResetEvent ent = new ManualResetEvent(false); public static void Main() { Boy sender = new Boy(ent); Thread th = new Thread(new ThreadStart(sender.SendFlower)); th.Start(); ent.WaitOne(); //等待工作 Console.WriteLine("收到了吧,花是我送嘀:)"); Console.ReadLine(); } } public class Boy { ManualResetEvent ent; public Boy(ManualResetEvent e) { ent = e; } public void SendFlower() { Console.WriteLine("正在送花的途中"); for (int i = 0; i <10; i++) { Thread.Sleep(200); Console.Write(".."); } Console.WriteLine(" 花已经送到MM手中了,boss"); ent.Set(); //通知阻塞程序 } } 而AutoResetEvent类故名思意,就是在每次Set完之后自动Reset。让执行程序重新进入阻塞状态。即AutoResetEvent.Set() 相当于 ManualResetEvent.Set() 之后又立即 ManualResetEvent.Reset(),其他的就没有什么不同的了。 |