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-Jun-2020

2K+ 瀏覽量

啟動你的 職業生涯

完成課程來獲得認證

開始
廣告