C# 裡的 Mutex 類是什麼?


C# 中的 Mutex 類是一種同步基元,它還可以用於程序間同步。

我們來看看如何建立一個新的 Mutex。

private static Mutex m = new Mutex();

現在我們來看如何用布林值初始化 Mutex 類的例項。

private static Mutex m = new Mutex(true);

現在讓我們看看如何用一個布林值和 Mutex 的名稱初始化 Mutex 類的例項。

示例

 線上演示

using System;
using System.Threading;

public class Demo {
   public static void Main() {
      Mutex mt = new Mutex(false, "NewMutex");
      Console.WriteLine("Waiting for the Mutex.");
      mt.WaitOne();
      Console.WriteLine("Owner of the mutex. " + "ENTER is to be pressed to release the mutexand          exit.");
      Console.ReadLine();
      mt.ReleaseMutex();
   }
}

輸出

Waiting for the Mutex.
Owner of the mutex. ENTER is to be pressed to release the mutex and exit.

更新於:22-06-2020

2k+ 瀏覽

開啟您的 職業生涯

完成課程即可獲得證書

開始
廣告