ManualResetEven使用的最清楚說明

ManualResetEven使用的最清楚說明c#

快速閱讀

理解ManualResetEvent,以及如何使用。api

官方說明

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

一個線程同步事件 ,經過發信號來控制線程來控制 是否有權限訪問 資源this

構造函數

初始化實例,而且指明信號的初始狀態 。線程

private static ManualResetEvent mre = new ManualResetEvent(false);

true:表示線程能夠訪問資源 ,就是能夠無視waitone裏的等待3d

false:表示線程若是碰到waitone的時候 ,就要暫停,等主線程來控制 。code

好比以下demo中,主線程調用線程執行如下方法時,若是默認是false,則只會輸入***starts and calls mre.WaitOne() 而沒有 ___ends的輸出,由於默認是false ,線程中的waitone()會阻止線程的繼續訪問 。blog

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() 阻止的一個或者多個線程進行執行線程中的代碼。three

這個上面的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.");
}

運行結果

友情提示

​ 我對個人文章負責,發現好多網上的文章 沒有實踐,都發出來的,讓人走不少彎路,若是你在個人文章中遇到沒法實現,或者沒法走通的問題。能夠直接在公衆號《愛碼農愛生活 》留言。一定會再次複查緣由。讓每一篇 文章的流程都能順利實現。

相關文章
相關標籤/搜索