C# | How to check current state of a thread
Last Updated :
01 Feb, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ThreadState to check the current state of the thread. The initial state of a thread is Unstarted state.
Syntax:
public ThreadState ThreadState{ get; }
Return Value: This property returns the value that indicates the state of the current thread.
Below programs illustrate the use of ThreadState property:
Example 1:
using System;
using System.Threading;
public class GFG {
static public void Main()
{
Thread thr;
thr = Thread.CurrentThread;
Console.WriteLine( "The name of the current state of the Main "
+ "thread is: {0}" , thr.ThreadState);
}
}
|
Output:
The name of the current state of the main thread is: Running
Example 2:
using System;
using System.Threading;
public class GFG {
public static void Main()
{
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);
TR1.Start();
Console.WriteLine( "ThreadState of TR1 thread " +
"is: {0}" , TR1.ThreadState);
TR2.Start();
Console.WriteLine( "ThreadState of TR2 thread" +
" is: {0}" , TR2.ThreadState);
}
public static void job()
{
Thread.Sleep(2000);
}
}
|
Output:
ThreadState of TR1 thread is: Unstarted
ThreadState of TR2 thread is: Unstarted
ThreadState of TR1 thread is: Running
ThreadState of TR2 thread is: WaitSleepJoin
Reference:
Share your thoughts in the comments
Please Login to comment...