没有 "Thread.Abort()" 立即停止 C# 线程

Stop C# thread immediately without "Thread.Abort()"

public class Worker
{
    private CancellationTokenSource cts;
    private Thread t;

    public Worker()
    {
        cts = new CancellationTokenSource();
        t = new Thread(() => { ThreadTask(cts.Token); });
    }

    ~Worker()
    {
        cts.Dispose();
    }

    private void ThreadTask(CancellationToken ct)
    {
        try
        {
            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    Debug.WriteLine("Cancelllation requested");
                    break;
                }

                // long task 1
                Debug.WriteLine("Task 1 completed");
                Thread.Sleep(2000);
                // long task 2
                Debug.WriteLine("Task 2 completed");
                Thread.Sleep(2000);
                // long task 3
                Debug.WriteLine("Task 3 completed");
                Thread.Sleep(2000);
                // long task 4
                Debug.WriteLine("Task 4 completed");
                Thread.Sleep(2000);
                Debug.WriteLine("All tasks completed");
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Thread exception: " + ex.ToString());
        }
        finally
        {
            // cleanup
            Debug.WriteLine("Thread cleanup");
        }
    }

    public void Start()
    {
        t.Start();
    }

    public void Stop()
    {
        cts.Cancel();
    }
}

我想知道是否可以在线程完成执行之前中断它。

例如,在上面描述的代码中,当调用函数Stop()时,线程会在执行结束时停止,我想更快地停止它,例如在“长任务”之间或即使 Thread.Sleep(2000).

一个解决方案可能是在调用 Stop() 时在任务线程中抛出异常,例如 Thread.Abort(),但是 Thread.Abort() 在 Net 6.0 上不起作用,我该怎么做那个?

环境:

您可以使用 Thread.Interrupt 方法。当前的 .NET 平台支持此 API。

Interrupts a thread that is in the WaitSleepJoin thread state.

If this thread is not currently blocked in a wait, sleep, or join state, it will be interrupted when it next begins to block.

ThreadInterruptedException is thrown in the interrupted thread, but not until the thread blocks. If the thread never blocks, the exception is never thrown, and thus the thread might complete without ever being interrupted.

您必须在 ThreadStart 委托主体内处理可能的 ThreadInterruptedException,否则在调用 Interrupt 时进程可能会崩溃。或者您可以像您目前所做的那样,使用通用 catch (Exception) 处理程序处理所有异常。