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

Kiểm tra trạng thái hiện tại của Thread trong C#

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ả
UnstartedLuồ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 ý

  • ThreadState là enum có flag (có thể kết hợp nhiều trạng thái).
  • Luồng từ ThreadPool luôn có IsThreadPoolThread = true.
  • Không nên dùng Thread.Abort(), Suspend(), Resume() (đã lỗi thời).