快速阅读

理解ManualResetEvent,以及如何使用。

官方说明

官方介绍:https://docs.microsoft.com/en-us/dotnet/api/system.threading.manualresetevent?view=netframework-1.1

一个线程同步事件 ,通过发信号来控制线程来控制 是否有权限访问 资源

构造函数

初始化实例,并且指明信号的初始状态 。

private static ManualResetEvent mre = new ManualResetEvent(false);

true:表示线程可以访问资源 ,就是可以无视waitone里的等待

false:表示线程如果碰到waitone的时候 ,就要暂停,等主线程来控制 。

比如如下demo中,主线程调用线程执行以下方法时,如果默认是false,则只会输入*starts and calls mre.WaitOne() 而没有 ___ends的输出,因为默认是false ,线程中的waitone()会阻止线程的继续访问 。

private static void ThreadProc()
{
    string name = Thread.CurrentThread.Name;

    Console.WriteLine(name + " starts and calls mre.WaitOne()");

    mre.WaitOne();

    Console.WriteLine(name + " ends.");
}

Set()方法

将事件状态设置为“已发送信号”,允许被waitone() 阻止的一个或者多个线程进行执行线程中的代码。

这个上面的demo中就会在调用mre.set()方法执行之后,会继续调用线程中的下面的___ends 的输出。

Reset()方法

将事件状态设置为“没信号”,这样线程中执行waitone()的时候 ,就会阴止当前线程的执行。实现了和构造函数传入默认值false一样的效果,不过它可以在执行的过程中,进行重新设置,表求又把线程调用组止了。

直接再次接收到set方法 。才会再次执行下面的访问 。

官方的demo

private static ManualResetEvent mre = new ManualResetEvent(false);

static void Main(string[] args)
{
    Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");

    for (int i = 0; i <= 2; i++)
    {
        Thread t = new Thread(ThreadProc);
        t.Name = "Thread_" + i;
        t.Start();
    }

    Thread.Sleep(500);
    Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" +
                      "\nto release all the threads.\n");
    Console.ReadLine();

    mre.Set();

    Thread.Sleep(500);
    Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +
                      "\ndo not block. Press Enter to show this.\n");
    Console.ReadLine();

    for (int i = 3; i <= 4; i++)
    {
        Thread t = new Thread(ThreadProc);
        t.Name = "Thread_" + i;
        t.Start();
    }

    Thread.Sleep(500);
    Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" +
                      "\nwhen they call WaitOne().\n");
    Console.ReadLine();

    mre.Reset();

    // Start a thread that waits on the ManualResetEvent.
    Thread t5 = new Thread(ThreadProc);
    t5.Name = "Thread_5";
    t5.Start();

    Thread.Sleep(500);
    Console.WriteLine("\nPress Enter to call Set() and conclude the demo.");
    Console.ReadLine();

    mre.Set();
}

private static void ThreadProc()
{
    string name = Thread.CurrentThread.Name;

    Console.WriteLine(name + " starts and calls mre.WaitOne()");

    mre.WaitOne();

    Console.WriteLine(name + " ends.");
}

运行结果

友情提示

​ 我对我的文章负责,发现好多网上的文章 没有实践,都发出来的,让人走很多弯路,如果你在我的文章中遇到无法实现,或者无法走通的问题。可以直接在公众号《爱码农爱生活 》留言。必定会再次复查原因。让每一篇 文章的流程都能顺利实现。


本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论