The cleanest way to stop a thread is by stopping them cooperatively, i.e. you pass an object to your thread to communicate that you want it to terminate. You can create one CancellationToken
and pass it to any third-party calls you're executing in your thread:
https://learn.microsoft.com/en-us/dotnet/standard/threading/using-threads-and-threading#how-to-stop-a-thread
https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads#code-example
Since .NET 5 the Thread.Abort
method throws this exception, so either the thread needs to be cancelled or it needs to be ran as part of a separate process. If you use a separate process you can call Process.Kill
to force it to terminate, although that may not be ideal depending on your application.