📜  C#|如何检查线程的当前状态

📅  最后修改于: 2021-05-29 23:55:05             🧑  作者: Mango

Thread类负责在多线程编程中创建和管理线程。它提供了一个称为ThreadState的属性来检查线程的当前状态。一个线程的初始状态是未开始状态。

句法:

public ThreadState ThreadState{ get; }

返回值:该属性返回指示当前线程状态的值。

下面的程序说明了ThreadState属性的用法:

范例1:

// C# program to illustrate the 
// use of ThreadState property
using System;
using System.Threading;
  
public class GFG {
  
    // Main Method
    static public void Main()
    {
        Thread thr;
  
        // Get the reference of main Thread
        // Using CurrentThread property
        thr = Thread.CurrentThread;
  
        // Display the current state
        // of the main thread
        Console.WriteLine("The name of the current state of the Main " 
                                 + "thread is: {0}", thr.ThreadState);
    }
}

输出:

The name of the current state of the main thread is: Running

范例2:

// C# program to illustrate the 
// use of ThreadState property
using System;
using System.Threading;
  
public class GFG {
  
    // Main method
    public static void Main()
    {
        // Creating and initializing threads
        Thread TR1 = new Thread(new ThreadStart(job));
        Thread TR2 = new Thread(new ThreadStart(job));
  
        Console.WriteLine("ThreadState of TR1 thread"+
                         " is: {0}", TR1.ThreadState);
  
        Console.WriteLine("ThreadState of TR2 thread"+
                         " is: {0}", TR2.ThreadState);
  
        // Running state
        TR1.Start();
        Console.WriteLine("ThreadState of TR1 thread "+
                           "is: {0}", TR1.ThreadState);
  
        TR2.Start();
        Console.WriteLine("ThreadState of TR2 thread"+
                         " is: {0}", TR2.ThreadState);
    }
  
    // Static method
    public static void job()
    {
        Thread.Sleep(2000);
    }
}

输出:

ThreadState of TR1 thread is: Unstarted
ThreadState of TR2 thread is: Unstarted
ThreadState of TR1 thread is: Running
ThreadState of TR2 thread is: WaitSleepJoin

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.threadstate?view=netframework-4.7.2