C# Program to Kill a Thread

This C# Program Kills a Thread. Here the working of the thread is stopped when a key is pressed else the work continues.

Here is source code of the C# Program to Kill a Thread. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*

* C# Program to Kill a Thread

*/

usingSystem;

usingSystem.Threading.Tasks;

usingSystem.Threading;

class Program

{

staticvoid Main(string[] args)

{

ThreadingClass th =new ThreadingClass();

Thread thread1 =new Thread(th.DoStuff);

thread1.Start();

Console.WriteLine("Press any key to exit!!!");

Console.ReadKey();

th.Stop();

thread1.Join();

}

}

publicclass ThreadingClass

{

privatebool flag =false;

publicvoid DoStuff()

{

while(!flag)

{

Console.WriteLine(" Thread is Still Working");

Thread.Sleep(1000);

}

}

publicvoid Stop()

{

flag =true;

}

}

Here is the output of the C# Program:

advertisement

Press any key to exit!!!
Thread is Still Working
Thread is Still Working
Thread is Still Working
Thread is Still Working
Thread is Still Working
Thread is Still Working
Thread is Still Working
Thread is Still Working
Thread is Still Working