C# 中的 Mutex 类是什么?

csharpprogrammingserver side programming更新于 2025/10/13 2:37:17

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.

相关文章