C# Program to Kill a Thread


Create a thread first and start it −

// new thread
Thread thread = new Thread(c.display);
thread.Start();

Now display the thread and set a stop function to stop the working of the thread −

public void display() {
   while (!flag) {
      Console.WriteLine("It's Working");
      Thread.Sleep(2000);
   }
}
public void Stop() {
   flag = true;
   }
}

Example

The following is the complete code to learn how to kill a thread in C#.

Live Demo

using System;
using System.Threading.Tasks;
using System.Threading;
class Demo {    
   static void Main(string[] args){
      MyClass c = new MyClass();      
      // new thread      
      Thread thread = new Thread(c.display);      
      thread.Start();      
      Console.WriteLine("Press any key to exit!");      
      Console.ReadKey();      
      c.Stop();      
       thread.Join();    
   }
}
public class MyClass {    
   private bool flag = false;    
   public void display() {      
      while (!flag) {        
         Console.WriteLine("It's Working");    
         Thread.Sleep(2000);      
       }    .
   }    .
   public void Stop() {      
      flag = true;    
   }
}

Output

It's Working
Press any key to exit!

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 19-Jun-2020

646 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements