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

Chương trình C# kiểm tra trạng thái luồng hiện tại (Thread.IsAlive)

Thuộc tính Thread.IsAlive trả về true nếu luồng đã được Start() và chưa kết thúc (chưa chạy xong phương thức entry, chưa bị abort).

Mã nguồn


using System;
using System.Threading;

namespace Demo {
    class MyClass {
        static void Main(string[] args) {
            // Luồng hiện tại (Main thread)
            Thread thread = Thread.CurrentThread;
            thread.Name = "My New Thread";
            
            // Luồng chính luôn IsAlive = true khi đang chạy Main
            Console.WriteLine("Trạng thái luồng = {0}", thread.IsAlive);
            Console.ReadKey();
        }
    }
}

Kết quả


Trạng thái luồng = True

Ví dụ thực tế: Kiểm tra worker thread


using System;
using System.Threading;

class Program {
    static void Main() {
        Thread worker = new Thread(DoWork);
        Console.WriteLine("Trước Start: IsAlive = {0}", worker.IsAlive); // False
        
        worker.Start();
        Console.WriteLine("Sau Start: IsAlive = {0}", worker.IsAlive);   // True
        
        Thread.Sleep(100); // Đợi worker chạy xong (DoWork nhanh)
        Console.WriteLine("Sau worker xong: IsAlive = {0}", worker.IsAlive); // False
        
        Console.ReadKey();
    }
    
    static void DoWork() {
        Thread.Sleep(50);
        Console.WriteLine("Worker done");
    }
}

Kết quả


Trước Start: IsAlive = False
Sau Start: IsAlive = True
Worker done
Sau worker xong: IsAlive = False

Các trạng thái Thread (ThreadState)

Thread.ThreadState cung cấp thông tin chi tiết hơn (bitmask):

Giá trịMô tả
UnstartedChưa gọi Start()
RunningĐang chạy
WaitSleepJoinĐang Sleep, Wait, Join
SuspendRequestedĐược yêu cầu Suspend (deprecated)
SuspendedĐã Suspend (deprecated)
AbortRequestedĐược yêu cầu Abort (deprecated)
StoppedĐã kết thúc

Lưu ý

  • IsAlive = true khi state là Running hoặc WaitSleepJoin.
  • IsAlive = false khi Unstarted hoặc Stopped.
  • Không thể restart thread đã Stopped — phải tạo thread mới.
  • Với Task: dùng task.IsCompleted, task.Status (TaskStatus enum).