码迷,mamicode.com
首页 > 其他好文 > 详细

WaitHandle——使用AutoResetEvent

时间:2015-01-21 22:27:45      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:多线程   线程   并发   线程安全   thread   



区别ManualResetEvent


     使用AutoResetEvent和使用ManualResetEvent是完全相同的,只有一点区别:在使用autoresetevent时,在调用waitOne后,会自动执行到一个reset方法。

  AutoResetEvent的waitone相当于将ManualResetEvent.waitone和reset合并为一个方法执行。

  需要注意:autoresetevent的waitone和reset合并为了一个原子操作;


  代码示例:



namespace 使用AutoResetEvent
{
    class Program
    {

        AutoResetEvent mre = new AutoResetEvent(false);


        static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "main ";
            Program p = new Program();
            Thread worker = new Thread(p.ThreadEntry);
            worker.Name = "worker";
            worker.Start();

            Console.WriteLine("main :start worker");
            p.mre.Set();
            Thread.Sleep(100);

            Console.WriteLine("main:worker go...");
            p.mre.Set();
            Thread.Sleep(100);


        }

        void ThreadEntry() {

            int i = 0;
            string name = Thread.CurrentThread.Name;
            while (i<10)
            {
                mre.WaitOne();   //这里实际上是waitone和reset************
                Console.WriteLine("{0}:{1}---{2}",name ,i,DateTime .Now .Millisecond);
                i++;

            }
        
        
        }
    }
}







WaitHandle——使用AutoResetEvent

标签:多线程   线程   并发   线程安全   thread   

原文地址:http://blog.csdn.net/lhc1105/article/details/42981057

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!