If you wish to terminate a thread in C#, you can use the Abort() method. Using Abort() with throw a ThreadAbortException, which will terminate the thread.
To show this in action, let's first create a thread:
using System;
using System.Threading;
class ThreadExample
{
public void MyThread()
{
for (int x = 0; x < 3; x++)
{
Console.WriteLine(x);
}
}
}
class MainClass
{
public static void Main()
{
var obj = new ThreadExample();
Thread thr = new Thread(new ThreadStart(obj.MyThread));
Console.WriteLine("Start the thread");
thr.Start();
Console.WriteLine("Finished!");
}
}
Start the thread
0
1
2
Finished!
If we call Abort() immediately after Start(), we can stop the thread from executing:
Console.WriteLine("Start the thread");
thr.Start();
Console.WriteLine("Abort the thread");
thr.Abort();
Console.WriteLine("Finished!");
Start the thread
Abort the thread
Finished!
It's important to note however, that if the thread that calls Abort() holds a lock, and the aborted thread requires that lock to be released, then a deadlock can occur.