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

Phương thức Join, Sleep, Abort trong Threading C#

Lớp Thread trong System.Threading cung cấp các phương thức quan trọng để điều khiển vòng đời và đồng bộ hóa luồng (thread).

1. Thread.Join()

Chặn luồng gọi (calling thread) cho đến khi luồng đích kết thúc. Có overload với timeout.

thread.Join();           // Chờ vô hạn
thread.Join(5000);       // Chờ tối đa 5 giây, trả về bool

2. Thread.Sleep()

Tạm dừng luồng hiện tại trong khoảng thời gian chỉ định.

Thread.Sleep(1000);      // Ngủ 1 giây (milliseconds)
Thread.Sleep(TimeSpan.FromSeconds(1));  // Dùng TimeSpan

3. Thread.Abort() (Đã lỗi thời - Obsolete)

⚠️ Không khuyến khích sử dụng từ .NET Core/.NET 5+. Buộc dừng luồng bằng cách ném ThreadAbortException. Gây rò rỉ tài nguyên, deadlock, trạng thái không nhất quán.

Ví dụ Join()

using System;
using System.Threading;

namespace Sample
{
    class Demo
    {
        static void Run()
        {
            for (int i = 0; i < 2; i++)
                Console.Write("Sample text!");
        }
        
        static void Main(string[] args)
        {
            Thread t = new Thread(Run);
            t.Start();
            t.Join();  // Main chờ t xong
            Console.WriteLine("Thread terminated!");
        }
    }
}

Ví dụ Sleep() và Abort() (chỉ để hiểu lịch sử)

using System;
using System.Threading;

namespace Demo
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            try
            {
                Console.WriteLine("Child thread starts");
                for (int counter = 0; counter <= 10; counter++)
                {
                    Thread.Sleep(500);
                    Console.WriteLine(counter);
                }
                Console.WriteLine("Child Thread Completed");
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine("Thread Abort Exception");
            }
            finally
            {
                Console.WriteLine("Couldn't catch the Thread Exception");
            }
        }
        
        static void Main(string[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Thread childThread = new Thread(childref);
            childThread.Start();
            
            Thread.Sleep(2000);  // Main ngủ 2s
            Console.WriteLine("In Main: Aborting the Child thread");
            childThread.Abort();  // ⚠️ Obsolete, không dùng trong production
            Console.ReadKey();
        }
    }
}

Thay thế cho Abort() - CancellationToken

// Cách hiện đại, an toàn
CancellationTokenSource cts = new CancellationTokenSource();
Thread t = new Thread(() => DoWork(cts.Token));
t.Start();

// Khi muốn dừng
cts.Cancel();  // Yêu cầu dừng hợp tác

void DoWork(CancellationToken token)
{
    while (!token.IsCancellationRequested)
    {
        // Làm việc...
        Thread.Sleep(100);
    }
    // Dọn dẹp tài nguyên
}

Tóm tắt

Phương thứcMục đíchTrạng thái
Join()Đồng bộ, chờ thread kết thúc✅ Khuyến khích
Sleep()Tạm dừng thread hiện tại✅ Khuyến khích (cẩn thận)
Abort()Buộc dừng thread❌ Obsolete, nguy hiểm
CancellationTokenYêu cầu dừng hợp tác✅ Best practice hiện đại