Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Kill a Thread
In C#, a thread can be gracefully stopped using a flag-based approach rather than forcibly terminating it. This method allows the thread to complete its current work and exit cleanly by checking a boolean flag in its loop condition.
The recommended approach involves setting a boolean flag that the thread periodically checks. When you want to stop the thread, you set the flag to true, causing the thread's loop to exit naturally.
Syntax
Following is the syntax for creating and controlling a thread with a stop flag −
Thread thread = new Thread(methodName); thread.Start(); // To stop the thread gracefully stopFlag = true; thread.Join(); // Wait for thread to finish
Key Components
Boolean Flag: A shared variable that signals when the thread should stop.
Loop Condition: The thread checks the flag in its main loop.
Join Method: Waits for the thread to complete before continuing.
Using Flag-Based Thread Control
The following example demonstrates how to create a thread and stop it gracefully using a boolean flag −
using System;
using System.Threading;
class Demo {
static void Main(string[] args) {
MyClass c = new MyClass();
// Create and start new thread
Thread thread = new Thread(c.Display);
thread.Start();
// Let thread run for 5 seconds
Thread.Sleep(5000);
Console.WriteLine("Stopping thread...");
// Stop the thread gracefully
c.Stop();
thread.Join();
Console.WriteLine("Thread stopped successfully.");
}
}
public class MyClass {
private bool flag = false;
public void Display() {
int counter = 1;
while (!flag) {
Console.WriteLine($"Thread working... {counter++}");
Thread.Sleep(1000);
}
Console.WriteLine("Thread is exiting...");
}
public void Stop() {
flag = true;
}
}
The output of the above code is −
Thread working... 1 Thread working... 2 Thread working... 3 Thread working... 4 Thread working... 5 Stopping thread... Thread is exiting... Thread stopped successfully.
Using CancellationToken
A more robust approach uses CancellationToken for thread cancellation −
using System;
using System.Threading;
class Program {
static void Main() {
CancellationTokenSource cts = new CancellationTokenSource();
Thread thread = new Thread(() => DoWork(cts.Token));
thread.Start();
Thread.Sleep(3000);
Console.WriteLine("Cancelling thread...");
cts.Cancel();
thread.Join();
Console.WriteLine("Thread completed.");
}
static void DoWork(CancellationToken token) {
try {
int count = 1;
while (!token.IsCancellationRequested) {
Console.WriteLine($"Working... {count++}");
Thread.Sleep(800);
}
} catch (OperationCanceledException) {
Console.WriteLine("Thread was cancelled.");
}
Console.WriteLine("Thread finished gracefully.");
}
}
The output of the above code is −
Working... 1 Working... 2 Working... 3 Working... 4 Cancelling thread... Thread finished gracefully. Thread completed.
Comparison of Thread Stopping Methods
| Method | Pros | Cons |
|---|---|---|
| Boolean Flag | Simple, lightweight, easy to understand | Manual flag management required |
| CancellationToken | Built-in framework support, more features | Slightly more complex setup |
| Thread.Abort() (Deprecated) | Immediate termination | Unsafe, can corrupt application state |
Conclusion
Graceful thread termination in C# is achieved using boolean flags or CancellationToken. These approaches allow threads to complete their current work and exit cleanly, avoiding the unsafe Thread.Abort() method. Always use thread.Join() to ensure the main thread waits for worker threads to complete.
