Giới thiệu
Thuộc tính ThreadState của lớp Thread (namespace System.Threading) cho biết trạng thái hiện tại của luồng: Unstarted, Running, WaitSleepJoin, Stopped, v.v. ManagedThreadId cho ID duy nhất do CLR gán.
Ví dụ 1: Luồng chưa start và ThreadPool
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(Demo1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Demo2));
Console.WriteLine("Trạng thái hiện tại của Thread = " + thread.ThreadState);
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
}
public static void Demo1()
{
Thread.Sleep(2000);
}
public static void Demo2(object stateInfo)
{
Console.WriteLine("Luồng thuộc managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
Kết quả
Trạng thái hiện tại của Thread = Unstarted
ManagedThreadId = 3
Luồng thuộc managed thread pool? = True
Ví dụ 2: Theo dõi trạng thái trước/sau Start
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(Demo));
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
Console.WriteLine("Trạng thái hiện tại của Thread = " + thread.ThreadState);
thread.Start();
Console.WriteLine("Trạng thái hiện tại của Thread = " + thread.ThreadState);
}
public static void Demo()
{
Console.WriteLine("Luồng thuộc managed thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
Kết quả
ManagedThreadId = 3
Trạng thái hiện tại của Thread = Unstarted
Luồng thuộc managed thread pool? = False
Trạng thái hiện tại của Thread = Running
Các giá trị ThreadState phổ biến
| Giá trị | Mô tả |
|---|---|
| Unstarted | Luồng vừa tạo, chưa Start |
| Running | Đang chạy |
| WaitSleepJoin | Đang chờ (Sleep, Join, Wait) |
| Stopped | Đã kết thúc |
| Suspended | Đã tạm dừng (Obsolete) |
| Aborted | Đã hủy (Abort - Obsolete) |
Lưu ý
ThreadStatelà enum có flag (có thể kết hợp nhiều trạng thái).- Luồng từ
ThreadPoolluôn cóIsThreadPoolThread = true. - Không nên dùng
Thread.Abort(),Suspend(),Resume()(đã lỗi thời).