/*
* Program to Kill a Thread in C#
*/
using System;
using System.Threading.Tasks;
using System.Threading;
class MyThread
{
private bool thread_flag = false;
public void ThreadFun()
{
while (thread_flag==false)
{
Console.WriteLine("->Thread is running");
Thread.Sleep(500);
}
}
public void Stop()
{
thread_flag = true;
}
}
class Program
{
static void Main(string[] args)
{
MyThread MT = new MyThread();
Thread T1 = new Thread(MT.ThreadFun);
T1.Start();
Console.WriteLine("Hit Any Key to finish execution!!!");
Console.ReadKey();
MT.Stop();
T1.Join();
}
}
Output:
Hit Any Key to finish execution!!!
->Thread is running
->Thread is running
->Thread is running
->Thread is running
Press any key to continue . . .
Explanation:
In the above program, we created a class MyThread that contains a method ThreadFun() and a boolean data member thread_flag to check the condition for the thread running status. We set thread_flag to "true" when the Stop method is called, then condition of while loop gets false and ThreadFun() method will be finished. When we HIT any key from the keyboard, after that Stop() method will call and stop the thread. If we will not press any key then the thread will execute indefinitely.
Program:
Output:
Explanation:
In the above program, we created a class MyThread that contains a method ThreadFun() and a boolean data member thread_flag to check the condition for the thread running status. We set thread_flag to "true" when the Stop method is called, then condition of while loop gets false and ThreadFun() method will be finished. When we HIT any key from the keyboard, after that Stop() method will call and stop the thread. If we will not press any key then the thread will execute indefinitely.