C# - How to Kidd a Thread?

Here, we are going to learn how to kill a thread in C#? By Nidhi Last updated : March 29, 2023

Killing a thread

To kill a thread, 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.

C# program to kill a thread

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.