1. 程式人生 > 程式設計 >C# ManualResetEvent用法詳解

C# ManualResetEvent用法詳解

ManualResetEvent表示執行緒同步事件,可以對所有進行等待的執行緒進行統一管理(收到訊號時必須手動重置該事件)

其建構函式為:

public ManualResetEvent (bool initialState);

引數 initialState 表示是否初始化,如果為 true,則將初始狀態設定為終止(不阻塞);如果為 false,則將初始狀態設定為非終止(阻塞)。

注意:如果其引數設定為true,則ManualResetEvent等待的執行緒不會阻塞。 如果初始狀態為false,則在Set呼叫方法之前,將阻止執行緒。

它只有兩個方法

//將事件狀態設定為終止狀態,從而允許繼續執行一個或多個等待執行緒。
public bool Set ();

//將事件狀態設定為非終止,從而導致執行緒受阻。
public bool Reset ();

//返回值:操作成功返回true,否則false

講了這麼多,看個例子理解一下

using System;
using System.Threading;

public class Example
{
  // mre is used to block and release threads manually. It is
  // created in the unsignaled state.
  private static ManualResetEvent mre = new ManualResetEvent(false);

  static void Main()
  {
    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();

    // If you run this example in Visual Studio,uncomment the following line:
    //Console.ReadLine();
  }


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

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

    mre.WaitOne(); //阻塞執行緒,直到呼叫Set方法才能繼續執行

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

結果如下

過程:

該示例以訊號狀態ManualResetEvent( false即傳遞給建構函式的) 開頭。 三個執行緒,每個執行緒在呼叫其WaitOne方法時被阻止。 當用戶按Enter鍵時,該示例呼叫Set方法,該方法釋放所有三個執行緒,使其繼續執行。

再次按 " enter " 鍵,此時ManualResetEvent在呼叫Reset方法之前,一直保持終止狀態,因此這些執行緒在呼叫WaitOne方法時不會被阻止,而是執行到完成。即對應上述(收到訊號時必須手動重置該事件)

再次按enter鍵將導致該示例呼叫Reset方法,並啟動一個執行緒,該執行緒在呼叫WaitOne時將被阻止。 按enter鍵,最後一次呼叫Set以釋放最後一個執行緒,程式結束。

如果還不是很清楚可以進行單步除錯,這樣就能明白了!

文章參考MSDN:ManualResetEvent Class

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。