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

Luồng và đồng bộ hóa luồng trong C#

Đồng bộ hóa đa luồng trong C#: lock, Mutex, Monitor, SemaphoreSlim, ReaderWriterLockSlim. ThreadPool quản lý pool luồng nền.

1. lock statement (cơ bản)

private readonly object _lock = new object();

public void SafeMethod()
{
    lock (_lock)
    {
        // Critical section - chỉ 1 luồng tại một thời điểm
    }
}

2. Mutex (cross-process)

// Named mutex - dùng cho single instance app
using (var mutex = new Mutex(true, "Global\\MyApp", out bool createdNew))
{
    if (!createdNew)
    {
        Console.WriteLine("Ứng dụng đã chạy!");
        return;
    }
    // Chạy ứng dụng...
    Console.ReadLine();
} // Tự động ReleaseMutex khi dispose

3. ThreadPool (quản lý luồng nền)

using System.Threading;

ThreadPool.QueueUserWorkItem(state => 
{
    // Chạy trên thread pool
    Console.WriteLine("Background work");
});

// Hoặc Task.Run (khuyên dùng .NET 4+)
Task.Run(() => Console.WriteLine("Task on ThreadPool"));

4. SemaphoreSlim (giới hạn độ song song)

var semaphore = new SemaphoreSlim(3); // Max 3 concurrent

await semaphore.WaitAsync();
try { /* work */ }
finally { semaphore.Release(); }

So sánh

Cơ chếPhạm viDùng cho
lockProcessCritical section ngắn
MutexCross-processSingle instance app, IPC
SemaphoreSlimProcessThrottling, resource pool
ReaderWriterLockSlimProcessĐọc nhiều, ghi ít
InterlockedProcessAtomic operations (int, ref)