How to check whether a thread is alive or not in C#
Last Updated :
11 Jan, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsAlive to check if the thread is alive or not. Or in other words, the value of this property indicates the current execution of the thread.
Syntax:
public bool IsAlive { get; }
Return Value: This property returns true if the thread is started and not terminated normally or aborted. Otherwise, return false. The return type of this property is System.Boolean.
Below programs illustrate the use of IsAlive property:
Example 1:
using System;
using System.Threading;
public class GFG {
static public void Main()
{
Thread thr;
thr = Thread.CurrentThread;
Console.WriteLine( "Is main thread is alive" +
" ? : {0}" , thr.IsAlive);
}
}
|
Output:
Is main thread is alive ? : True
Example 2:
using System;
using System.Threading;
public class GFG {
public static void Main()
{
Thread Thr1 = new Thread( new ThreadStart(job));
Thread Thr2 = new Thread( new ThreadStart(job));
Console.WriteLine( "Is thread 1 is alive : {0}" ,
Thr1.IsAlive);
Console.WriteLine( "Is thread 2 is alive : {0}" ,
Thr2.IsAlive);
Thr1.Start();
Thr2.Start();
Console.WriteLine( "Is thread 1 is alive : {0}" ,
Thr1.IsAlive);
Console.WriteLine( "Is thread 2 is alive : {0}" ,
Thr2.IsAlive);
}
public static void job()
{
Thread.Sleep(2000);
}
}
|
Output:
Is thread 1 is alive : False
Is thread 2 is alive : False
Is thread 1 is alive : True
Is thread 2 is alive : True
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...