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

Đồng bộ hóa và Thread Pool trong C#

Kết hợp đồng bộ hóa (lock, Mutex) với ThreadPool để quản lý công việc nền hiệu quả.

ThreadPool - Pool luồng nền

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine($"ThreadPool threads: {ThreadPool.ThreadCount}");
        Console.WriteLine($"Available: worker={ThreadPool.GetAvailableThreads(out int _, out int _)}");
        
        // Hàng đợi công việc
        for (int i = 0; i < 10; i++)
        {
            int taskId = i;
            ThreadPool.QueueUserWorkItem(state => 
            {
                Thread.Sleep(100); // Giả lập work
                Console.WriteLine($"Task {taskId} done on thread {Thread.CurrentThread.ManagedThreadId}");
            });
        }
        
        Thread.Sleep(2000); // Đợi hoàn thành
        Console.WriteLine("All done");
    }
}

Kết hợp với đồng bộ hóa

using System;
using System.Threading;

class SharedResource
{
    private int _value = 0;
    private readonly object _lock = new object();
    // Hoặc: private readonly Mutex _mutex = new Mutex();
    
    public void Increment()
    {
        lock (_lock) // Hoặc _mutex.WaitOne() / _mutex.ReleaseMutex()
        {
            _value++;
            Console.WriteLine($"Value: {_value} (Thread: {Thread.CurrentThread.ManagedThreadId})");
        }
    }
}

class Program
{
    static void Main()
    {
        var resource = new SharedResource();
        
        for (int i = 0; i < 5; i++)
        {
            ThreadPool.QueueUserWorkItem(_ => resource.Increment());
        }
        
        Thread.Sleep(500);
    }
}

ThreadPool vs Task

ThreadPoolTask (TPL)
QueueUserWorkItem (callback)Task.Run, async/await
Không trả về kết quả dễ dàngTask<TResult>, continuation
Khó xử lý exceptionException handling tự nhiên
Khó cancelCancellationToken support
Legacy APIModern API (.NET 4+)

Khuyến nghị: Dùng Task.Run / async-await thay vì ThreadPool.QueueUserWorkItem cho code mới.