Thread类负责在多线程编程中创建和管理线程。它提供了一个称为IsAlive的属性来检查线程是否处于活动状态。换句话说,此属性的值指示线程的当前执行。
句法:
public bool IsAlive { get; }
返回值:如果线程已启动且未正常终止或中止,则此属性返回true。否则,返回false 。此属性的返回类型为System.Boolean 。
下面的程序说明了IsAlive属性的用法:
范例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/zh-cn/dotnet/api/system.threading.thread.isalive?view=netframework-4.7.2