How to Terminate a Thread in C#?
Last Updated :
03 Feb, 2025
In C#, threads are used to achieve tasks concurrently, a fundamental feature in multithreading and parallel programming. However, there are scenarios where we need to terminate a thread. There are different ways to terminate a thread and in this article, we will discuss those ways with their code implementation.
Ways to Terminate Thread
- Abort Method
- Abort Object
- CancellationToken
- Manually
1. Using Abort Method
The Abort()
method throws a ThreadAbortException
to the thread in which it is called, forcing the thread to terminate. However, this method is deprecated due to unpredictable behavior and is no longer recommended for use in modern versions of .NET.
Syntax:
public void Abort();
Exceptions:
- SecurityException: If the caller does not have the required permission.
- ThreadStateException: If the thread that is being aborted is currently suspended.
Example:
C#
// C# program to illustrate the
// concept of Abort() method
// on a single thread
using System;
using System.Threading;
class ExampleofThread
{
// Non-Static method
public void thread()
{
for (int x = 0; x < 3; x++)
{
Console.WriteLine(x);
}
}
}
class Geeks
{
public static void Main()
{
// Creating instance for mythread() method
ExampleofThread o = new ExampleofThread();
// Creating and initializing threads
Thread thr = new Thread(new ThreadStart(o.thread));
thr.Start();
Console.WriteLine("Thread is abort");
// Abort the thread
// Using Abort() method
thr.Abort();
}
}
Output:

Explanation: The above example shows the use of the Abort() method which is provided by the Thread class. By using thr.Abort(); statement, we can terminate the execution of the thread.
Note: This method is deprecated and no longer in used in newer versions. Instead of abort method we can use other alternatives to avoid the warnings.
2. Using Abort Object
This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Same as Abort method this is also not recommended to use.
Syntax:
public void Abort(object information);
Here, the information contains any information that you want to pass in a thread when it is being stopped. This information is only accessible by using the ExceptionState property of ThreadAbortException.
Exceptions:
- SecurityException: If the caller does not have the required permission.
- ThreadStateException: If the thread that is being aborted is currently suspended.
Example:
C#
// C# program to illustrate the
// concept of Abort(object)
using System;
using System.Threading;
class ExThread
{
public Thread thr;
public ExThread(string name)
{
thr = new Thread(this.RunThread);
thr.Name = name;
thr.Start();
}
void RunThread()
{
try
{
Console.WriteLine(thr.Name +
" is starting.");
for (int j = 1; j < 10; j++)
{
Console.Write(j + " ");
if ((j % 2) == 0)
{
Console.WriteLine();
Thread.Sleep(100);
}
}
Console.WriteLine(thr.Name +
" exiting normally.");
}
catch (ThreadAbortException ex)
{
Console.WriteLine("Thread is aborted and the code is "
+ ex.ExceptionState);
}
}
}
class Geeks
{
static void Main()
{
// Creating object of ExThread
ExThread obj = new ExThread("Thread ");
Thread.Sleep(1000);
Console.WriteLine("Stop thread");
obj.thr.Abort(100);
// Waiting for a thread to terminate.
obj.thr.Join();
Console.WriteLine("Main thread is terminating");
}
}
Output:

Note: Abort(Object) is also not in used in newer versions and if we try to to execute the above program it will give the warning as shown in the output picture.
3. Using CancellationToken
CancellationToken allows us to politely request that a thread should stop its work. It is recommended to use in newer versions. We need to create a CancellationTokenSource object and pass its token to the thread.
Syntax
CancellationTokenSource tokenSource = new CancellationTokenSource(); // create object
Thread workerThread = new Thread(() => LongRunningOperation(tokenSource.Token));
if (token.IsCancellationRequested)
{
// Perform cleanup and exit
return;
}
tokenSource.Cancel();
Example:
C#
// Illustration of Thread termination using cancellation tokens
using System;
using System.Threading;
public class ThreadWorker
{
public void DoWork(CancellationToken ct)
{
for (int i = 1; i < 3; i++)
{
if (ct.IsCancellationRequested)
{
Console.WriteLine("Cancellation requested, terminating the thread.");
return;
}
Console.WriteLine($"Working... Step {i + 1}");
Thread.Sleep(100);
}
Console.WriteLine("Work completed.");
}
}
public class Geeks
{
public static void Main()
{
CancellationTokenSource Cts = new CancellationTokenSource();
CancellationToken ct = Cts.Token;
Thread thr = new Thread(() => new ThreadWorker().DoWork(ct));
thr.Start();
Thread.Sleep(100);
Cts.Cancel();
thr.Join();
Console.WriteLine("Main thread exits.");
}
}
OutputWorking... Step 2
Cancellation requested, terminating the thread.
Main thread exits.
4. Mannual Termination
We can also terminate a thread manually just like creating a flag that the thread checks regularly to see if it should stop. This is a manual and simple method, but it requires the thread to periodically check the flag and decide when to exit.
Syntax
private volatile bool stopRequested; // Flag to signal thread termination
public void DoWork()
{
while (!stopRequested) // Check flag periodically
{
// Thread work here
Console.WriteLine(“Working…”);
Thread.Sleep(100); // Simulate work
}
}
public void RequestStop() => stopRequested = true;
Example:
C#
// Terminating the thread using Flag
using System;
using System.Threading;
public class ThreadWorker
{
private bool stopRequested = false;
public void DoWork()
{
for (int i = 0; i < 3; i++)
{
if (stopRequested)
{
Console.WriteLine("Stop requested, terminating the thread.");
return;
}
Console.WriteLine($"Working... Step {i + 1}");
Thread.Sleep(100);
}
Console.WriteLine("Work completed.");
}
public void RequestStop()
{
stopRequested = true;
}
}
public class Geeks
{
public static void Main()
{
ThreadWorker wrk = new ThreadWorker();
Thread wrkThread = new Thread(wrk.DoWork);
wrkThread.Start();
// Simulate some work
Thread.Sleep(200);
// Request the wrk thread to stop
wrk.RequestStop();
// Wait for the wrk thread to finish
wrkThread.Join();
Console.WriteLine("Main thread exits.");
}
}
OutputWorking... Step 1
Working... Step 2
Stop requested, terminating the thread.
Main thread exits.
Key Points
- A deadlock can occur if the thread that calls Abort methods holds a lock that the aborted thread requires.
- If the Abort method is called on a thread which has not been started, then that thread will abort when Start is called.
- If the Abort method is called on a thread which is blocked or is sleeping then the thread will get interrupted and after that get aborted.
- Calling Abort on a suspended thread throws a ThreadStateException in the calling thread and adds AbortRequested to the state of the aborted thread.
- A ThreadAbortException is not thrown in the suspended thread until Resume is called.
- If the Abort method is called on a Managed thread which is currently executing unmanaged code then a ThreadAbortException is not thrown until the thread returns to managed code.
- If two calls to Abort come at the same time then it is possible for one call to set the state information and the other call to execute the Abort. However, an application cannot detect this situation.
- After Abort is invoked on a thread, its state shows AbortRequested. Once terminated due to Abort, the state switches to Stopped. If permitted, the target thread can cancel the abort with ResetAbort.
Similar Reads
How to Create Threads in C#?
Multithreading enables concurrent task execution in C#. It improves performance and responsiveness. We can create threads using the System.Threading namespace. With the help of Threads, we can achieve multitasking and can define their behavior using different methods provided by the Thread Class. Ex
6 min read
C# | How to check current state of a thread
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ThreadState to check the current state of the thread. The initial state of a thread is Unstarted state. Syntax: public ThreadState ThreadState{ get; } Return Value: This prop
2 min read
How to Thread Lock Work in C#?
C# makes the concurrent execution of a code possible with the help of threads. The namespace System. Threading which is pre-built in C# supports the use of threads. Typically we create threads for the concurrent execution of a program. But in certain cases we may not want our program to be run concu
4 min read
How to Schedule a Thread for Execution in C#?
In C#, we can schedule a thread for execution using the Thread class. The Thread.Start() method is responsible for scheduling a thread, allowing it to run when system resources are available. This method can be overloaded to pass parameters to the thread. Also, the Thread.Sleep() method can be used
3 min read
How to Check Whether a Thread is Alive or Not in C#?
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as IsAlive to check if the thread is alive or not. In other words, the value of this property indicates the current execution of the thread. Example 1: This example demonstrates
3 min read
C# Joining Threads
In C#, multiple threads can be created and run concurrently to perform parallel tasks. Sometimes it is necessary to wait for one thread to finish its execution before proceeding or for all threads to complete before continuing further. The Thread.Join() method allows one thread to wait for another t
5 min read
How to get Synchronize access to the Queue in C#
Queue.SyncRoot Property is used to get an object which can be used to synchronize access to the Queue. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remov
2 min read
How to create a Queue in C#
Queue() Constructor is used to initializes a new instance of the Queue class which will be empty, and will have the default initial capacity, and uses the default growth factor. Queue represents a first-in, first out collection of object. It is used when you need first-in, first-out access of items.
2 min read
C# Main Thread
In C#, threads are the smallest units of execution that allow parallel execution of code, enabling multiple tasks to run concurrently within a single process. The Thread class in the System.Threading namespace is used to create and manage threads. In C#, the Main method is the entry point of any con
5 min read
Console.Read() Method in C#
Console.Read() Method is used to read the next character from the standard input stream. This method basically blocks its return when the user types some input characters. As soon as the user press ENTER key it terminates. Syntax: public static int Read (); Return Value: It returns the next characte
1 min read