Computer >> Máy Tính >  >> Lập trình >> C#

Lớp Mutex trong C # là gì?

Lớp Mutex trong C # là lớp nguyên thủy đồng bộ hóa cũng có thể được sử dụng để đồng bộ hóa liên quá trình.

Hãy để chúng tôi xem cách tạo Mutex mới.

private static Mutex m = new Mutex();

Bây giờ chúng ta hãy xem cách khởi tạo một phiên bản mới của lớp Mutex với giá trị Boolean.

private static Mutex m = new Mutex(true);

Bây giờ chúng ta hãy xem cách khởi tạo một phiên bản mới của lớp Mutex với giá trị Boolean và tên của Mutex.

Ví dụ

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();
   }
}

Đầu ra

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