个性化阅读
专注于IT技术分析

如何在C#中检查线程是否处于活动状态?

Thread类负责在多线程编程中创建和管理线程。它提供了一个称为活着检查线程是否处于活动状态。换句话说, 此属性的值指示线程的当前执行。

语法如下:

public bool IsAlive { get; }

返回值:该属性返回true如果线程已启动且未正常终止或中止。否则, 返回false。此属性的返回类型为System.Boolean.

以下程序说明了活着属性:

范例1:

// C# program to illustrate the 
// use of IsAlive 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 Using IsAlive
         // property
         Console.WriteLine( "Is main thread is alive" +
                             " ? : {0}" , thr.IsAlive);
     }
}

输出如下:

Is main thread is alive ? : True

范例2:

// C# program to illustrate the 
// use of IsAlive property
using System;
using System.Threading;
  
public class GFG {
  
     // Main method
     public static void Main()
     {
         // Creating and initializing threads
         Thread Thr1 = new Thread( new ThreadStart(job));
         Thread Thr2 = new Thread( new ThreadStart(job));
  
         // Display the current state of 
         // the threads Using IsAlive 
         // property
         Console.WriteLine( "Is thread 1 is alive : {0}" , Thr1.IsAlive);
  
         Console.WriteLine( "Is thread 2 is alive : {0}" , Thr2.IsAlive);
         Thr1.Start();
         Thr2.Start();
  
         // Display the current state of 
         // the threads Using IsAlive
         // property
         Console.WriteLine( "Is thread 1 is alive : {0}" , Thr1.IsAlive);
  
         Console.WriteLine( "Is thread 2 is alive : {0}" , Thr2.IsAlive);
     }
  
     // Static method
     public static void job()
     {
         Thread.Sleep(2000);
     }
}

输出如下:

Is thread 1 is alive : False
Is thread 2 is alive : False
Is thread 1 is alive : True
Is thread 2 is alive : True

参考:

  • https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.isalive?view=netframework-4.7.2

赞(0) 打赏
未经允许不得转载:srcmini » 如何在C#中检查线程是否处于活动状态?
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏