WaitHandle——使用AutoResetEvent

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



区别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++;

            }
        
        
        }
    }
}







目录
相关文章
|
4月前
|
C#
C# | 使用AutoResetEvent和ManualResetEvent进行线程同步和通信
在多线程编程中,AutoResetEvent 和 ManualResetEvent 是两个常用的同步原语。它们用于线程间的通信和协调,以确保线程按照特定的顺序执行。本篇博客将介绍这两种同步原语的概念、用法和区别。
46 0
C# | 使用AutoResetEvent和ManualResetEvent进行线程同步和通信
|
Java
线程中断方法interrupt、isInterrupted、interrupted方法
线程中断方法interrupt、isInterrupted、interrupted方法
86 0
线程中断方法interrupt、isInterrupted、interrupted方法
C#深入理解AutoResetEvent和ManualResetEvent
当在C#使用多线程时就免不了使用AutoResetEvent和ManualResetEvent类,可以理解这两个类可以通过设置信号来让线程停下来或让线程重新启动,其实与操作系统里的信号量很相似(汗,考完考试已经有点忘记了)。
1852 0
|
API iOS开发
RunLoop
简介 什么是 RunLoop ? 从字面意思看的话是运行循环、跑圈的意思; RunLoop 的基本作用是什么: 保持程序的持续运行; 处理 App 中的各种事件(比如触摸事件、定时器事件、Selector 事件); 节省 CPU 资源,提高程序性能:...
1111 0