ADVERTISEMENT
ADVERTISEMENT

C# program to kill a thread

C# | Kill a thread: Here, we are going to learn how to kill a thread in C#?
Submitted by Nidhi, on August 16, 2020

To solve the above problem, here we implemented the program to stop running thread when a key is pressed by the user, if the user will not press the key then thread will run indefinitely.

Program:

/*
 * 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.

C# Thread Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.