Users Online

· Guests Online: 28

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C# Program to Kill a Thread

C# Program to Kill a Thread

 

This is a C# Program to kill a thread.

Problem Description

This C# Program Kills a Thread.

Problem Solution

Here the working of the thread is stopped when a key is pressed else the work continues.

Program/Source Code

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
 */
using System;
using System.Threading.Tasks;
using System.Threading;
class Program  
{  
     static void 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();  
     }   
}
public class ThreadingClass  
{  
     private bool flag = false;  
    public void DoStuff()  
    {  
         while (!flag)  
         {  
             Console.WriteLine(" Thread is Still Working");  
             Thread.Sleep(1000);  
         }  
     }  
    public void Stop()  
     {  
         flag = true;  
     }  
 }
Program Explanation

In this C# Program, we are creating an object ‘th’ for ThreadingClass. then we are creating a new thread named as thread1 by calling the DoStuff() function in threading class. Using while loop in Dostuff() function check the thread is still working by checking the condition of the value of ‘flag’ variable is equal to true.

 

If the condition is true, then execute the statement and print the statement as Thread is Still Working. The sleep() method is used for making a thread pause for a specific period of time. Here the working of the thread is stopped when a key is pressed else the work continues.

Runtime Test Cases
 
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

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.71 seconds
10,858,190 unique visits