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ả |
|---|---|
Unstarted | Chư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 = truekhi state làRunninghoặcWaitSleepJoin.IsAlive = falsekhiUnstartedhoặcStopped.- Không thể restart thread đã Stopped — phải tạo thread mới.
- Với
Task: dùngtask.IsCompleted,task.Status(TaskStatusenum).