Thread.Abort() is not support at .NET5/6.
When thread work function can not "return", dead locked. How to kill classic thread task?
static void Main()
{
Thread thread = new Thread(Work);
thread.Start();
try
{
//not support
thread.Abort();
}
catch(Exception ex)
{
//System.PlatformNotSupportedException
Console.WriteLine(ex.Message);
}
//not abort
thread.Join();
}
static void Work()
{
// work function without "return", dead locked
while(true)
{
Thread.Sleep(1000000);
}
}
CodePudding user response:
For lots of reasons, you can't immediately kill a thread in C#, however you can modify the logic a little bit to stop the thread.
First, you need to add a flag (of any type) to indicate the continuity of the thread
private static bool shouldRun=true;
static void Main()
{
Thread thread = new Thread(Work);
thread.Start();
try
{
//not support
//thread.Abort();
shouldRun=false;
}
catch(Exception ex)
{
//System.PlatformNotSupportedException
Console.WriteLine(ex.Message);
}
//not abort
thread.Join();
}
static void Work()
{
// work function without "return", dead locked
while(shouldRun)
{
Thread.Sleep(1000000);
}
}
CodePudding user response:
Thread.Abort() used to work when carefully Handled. There is no discussion: Thread.Abort() is a dangerous API that throws ThreadAbortException at any random point deep in the call stack. Nevertheless production logs show that when carefully implemented Thread.Abort() doesn’t provoke any crash nor state corruption.
CancellationToken is nowadays the safe way to implement cancelable operations. But it is not a replacement for Thread.Abort(): it only supports co-operative cancellation scenarios, where the cancellable processing is responsible for periodically checking if it has been cancelled.
if(cancelToken.IsCancellationRequested){
throw new TaskCancelledException();
}
