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.
廣告