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

Phương thức và thuộc tính của lớp Thread trong C#

Lớp System.Threading.Thread đại diện cho một luồng thực thi. Dưới đây là các thành viên quan trọng (đã cập nhật cho .NET hiện đại).

Thuộc tính (Properties) chính

Thuộc tínhKiểuMô tả
CurrentThreadThread (static)Luồng đang chạy code hiện tại.
ManagedThreadIdintID duy nhất của managed thread (không thay đổi).
NamestringTên luồng (debugging). Chỉ set 1 lần.
IsAliveboolTrue nếu thread đã Start và chưa terminated.
IsBackgroundboolTrue = background thread (không giữ process sống). Default: false.
ThreadStateThreadStateTrạng thái bitmask: Running, WaitSleepJoin, Suspended, Stopped...
PriorityThreadPriorityĐộ ưu tiên: Lowest, BelowNormal, Normal, AboveNormal, Highest.
CurrentCultureCultureInfoCulture cho formatting/parsing (thread-local).
CurrentUICultureCultureInfoCulture cho resource lookup (localization).
ExecutionContextExecutionContextContext bảo mật, synchronization, call context.

Phương thức (Methods) chính

Phương thứcMô tả
Start()Bắt đầu thực thi thread (gọi delegate).
Start(object)Bắt đầu với tham số (ParameterizedThreadStart).
Join()Block caller cho đến khi thread kết thúc. Có overload timeout.
Sleep(ms)(Static) Tạm dừng thread hiện tại (ms).
Yield()(Static) Nhường CPU cho thread khác cùng priority.
Abort()Deprecated (.NET Core/.NET 5+). Ném ThreadAbortException. Không dùng.
Interrupt()Đánh thức thread đang Wait/Sleep/Join (ném ThreadInterruptedException).
GetApartmentState()Trả về STA/MTA/Unknown (COM interop).
SetApartmentState()Set STA/MTA (trước Start).
BeginCriticalRegion()(Static) Thông báo host: region nhạy cảm (SQL, lock).
EndCriticalRegion()(Static) Kết thúc critical region.

Ví dụ: Demo các thuộc tính/phương thức

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine($"Main Thread ID: {Thread.CurrentThread.ManagedThreadId}");
        
        Thread t = new Thread(Worker)
        {
            Name = "MyWorker",
            IsBackground = true, // Không chặn app exit
            Priority = ThreadPriority.AboveNormal
        };
        
        Console.WriteLine($"Before Start: IsAlive={t.IsAlive}, State={t.ThreadState}");
        t.Start("Hello from worker");
        Console.WriteLine($"After Start: IsAlive={t.IsAlive}, State={t.ThreadState}");
        
        t.Join(); // Đợi kết thúc
        Console.WriteLine($"After Join: IsAlive={t.IsAlive}, State={t.ThreadState}");
    }
    
    static void Worker(object data)
    {
        Console.WriteLine($"[{Thread.CurrentThread.Name}] ID={Thread.CurrentThread.ManagedThreadId}, Data={data}");
        Thread.Sleep(1000);
        Console.WriteLine($"[{Thread.CurrentThread.Name}] Done");
    }
}

Kết quả

Main Thread ID: 1
Before Start: IsAlive=False, State=Unstarted
After Start: IsAlive=True, State=Running
[MyWorker] ID=4, Data=Hello from worker
[MyWorker] Done
After Join: IsAlive=False, State=Stopped

Lưu ý quan trọng (.NET Core / .NET 5+)

  • Thread.Abort() không được hỗ trợ (ném PlatformNotSupportedException). Dùng CancellationToken.
  • Thread.Suspend/Resume deprecated từ lâu (deadlock risk).
  • Ưu tiên Task, async/await, Parallel, ThreadPool thay vì quản lý Thread thủ công.
  • ThreadLocal<T> cho thread-local storage.