天天看點

ManualResetEven使用的最清楚說明

ManualResetEven使用的最清楚說明

快速閱讀

了解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.");
}
           

運作結果

ManualResetEven使用的最清楚說明

友情提示

​ 我對我的文章負責,發現好多網上的文章 沒有實踐,都發出來的,讓人走很多彎路,如果你在我的文章中遇到無法實作,或者無法走通的問題。可以直接在公衆号《愛碼農愛生活 》留言。必定會再次複查原因。讓每一篇 文章的流程都能順利實作。

ManualResetEven使用的最清楚說明

作者:水木    

出處:http://www.hechunbo.com/