Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lớp Mutex trong C#

Mutex (Mutual Exclusion) - nguyên ngữ đồng bộ hóa có thể dùng cross-process (giữa các tiến trình).

Khởi tạo Mutex

// Unnamed mutex (chỉ trong process)
Mutex localMutex = new Mutex();

// Named mutex (cross-process)
Mutex namedMutex = new Mutex(false, "MyAppMutex");

// Named mutex + sở hữu ban đầu
Mutex ownedMutex = new Mutex(true, "MyAppMutex", out bool createdNew);

Ví dụ: Single Instance Application

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        // Thử tạo named mutex
        using (var mutex = new Mutex(true, "Global\\MyUniqueAppName", out bool createdNew))
        {
            if (!createdNew)
            {
                Console.WriteLine("Ứng dụng đã đang chạy!");
                Console.ReadLine();
                return;
            }
            
            Console.WriteLine("Ứng dụng khởi động. Nhấn Enter để thoát...");
            Console.ReadLine();
        } // Mutex tự động Release khi dispose
    }
}

Ví dụ: Đồng bộ hóa cơ bản

using System;
using System.Threading;

class Program
{
    static Mutex mutex = new Mutex();
    static int counter = 0;
    
    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            new Thread(Worker).Start(i);
        }
        Thread.Sleep(1000);
        Console.WriteLine($"Counter cuối: {counter}"); // 500000
    }
    
    static void Worker(object id)
    {
        for (int i = 0; i < 100000; i++)
        {
            mutex.WaitOne();
            counter++;
            mutex.ReleaseMutex();
        }
    }
}

So sánh lock vs Mutex: lock nhẹ hơn, chỉ trong process. Mutex nặng hơn, cross-process, có thể named, hỗ trợ WaitOne timeout, abandon detection.