How to Terminate a Thread in C#

01 Feb, 2019
In C#, a thread can be terminated using Abort() method. Abort() throws ThreadAbortException to the thread in which it called. Due to this exception, the thread is terminated. There are two methods in the overload list of Thread.Abort Method as follows:
Abort()Abort(Object)
Abort()
Abort(Object)
This method raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Generally, this method is used to terminate the thread.
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# program to illustrate the// concept of Abort() method// on a single threadusing System;using System.Threading;  class ExampleofThread {      // Non-Static method    public void thread()    {        for (int x = 0; x < 3; x++) {            Console.WriteLine(x);        }    }}  // Driver Classclass ThreadExample {      // Main method    public static void Main()    {          // Creating instance for mythread() method        ExampleofThread obj = new ExampleofThread();          // Creating and initializing threads        Thread thr = new Thread(new ThreadStart(obj.thread));        thr.Start();          Console.WriteLine("Thread is abort");          // Abort thr thread        // Using Abort() method        thr.Abort();    }}
Output:
Thread is abort

Explanation: The above example shows the use of Abort() method which is provided by the Thread class. By using thr.Abort(); statement, we can terminate the execution of thr thread.
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. Generally, this method is used to terminate the thread.
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 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# 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();    }      // Enetring point for thread    void RunThread()    {        try {            Console.WriteLine(thr.Name +                        " is starting.");              for (int j = 1; j <= 100; j++)             {                Console.Write(j + " ");                if ((j % 10) == 0)                 {                    Console.WriteLine();                    Thread.Sleep(200);                }            }            Console.WriteLine(thr.Name +                   " exiting normally.");        }        catch (ThreadAbortException ex) {            Console.WriteLine("Thread is aborted and the code is "                                             + ex.ExceptionState);        }    }}  // Driver Classclass GFG {      // Main method    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:
Thread  is starting.
1 2 3 4 5 6 7 8 9 10 
11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 
41 42 43 44 45 46 47 48 49 50 
Stop thread
Thread is aborted and the code is 100
Main thread is terminating

Important 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.
If Abort method is called on a suspended thread then a ThreadStateException is thrown in the thread that called Abort, and AbortRequested is added to the ThreadState property of the thread being aborted.
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. But, an application cannot detect this situation.
After Abort is called on a thread, the state of the thread includes AbortRequested. After the thread has terminated due to the result of a successful call to Abort, the state of the thread is changed to Stopped. With sufficient permissions, a thread which is the target of an Abort can cancel the abort using the ResetAbort method.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.abort?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.