当线程终止时,.Join()调用永远不会被解除阻止

本文关键字:永远 调用 终止 线程 Join | 更新日期: 2023-09-27 18:24:03

我使用.Abort().Join()停止线程执行,等待线程终止。但问题是.Join()从未解除对应用程序的阻止,线程终止时也是如此。为什么?我的代码:

  th.Abort();
  Console.WriteLine("request sent, please wait..");
  th.Join();
  Console.WriteLine("done!");

上面的代码从未解锁应用程序,但它运行良好:

th.Abort();
Console.WriteLine("request sent, please wait..");
while (serverTh.ThreadState != ThreadState.Aborted) {
          Thread.Sleep(500);
 }
 Console.WriteLine("done!");

提前谢谢。

当线程终止时,.Join()调用永远不会被解除阻止

您试图中止的线程中发生了什么?例如,这很好:

    public static void Main(String[] args)
    {
        var t = new Thread(LoopForever);
        t.Start();
        Thread.Sleep(500);
        Console.WriteLine("request sent, please wait..");
        t.Abort();
        t.Join();
        Console.WriteLine("done!");
        Console.ReadLine();
    }
    public static void LoopForever()
    {
        Console.WriteLine("Running!");
        while (true)
        {
            Thread.Sleep(100);
            Console.WriteLine("Running!");
        }
    }

唯一能想到的可能是,您的后台线程正在捕获AbortException,然后在自身上调用ResetArtrt:

    public static void Main(String[] args)
    {
        var t = new Thread(LoopForever);
        t.Start();
        // Let the thread get started...
        Thread.Sleep(500);
        Console.WriteLine("request sent, please wait..");
        t.Abort();
        t.Join();
        Console.WriteLine("done!");
        Console.ReadLine();
    }
    public static void LoopForever()
    {
            Console.WriteLine("Running!");
            while (true)
            {
                try
                {
                    Console.WriteLine("Running!");
                    Thread.Sleep(100);
                }
                catch (ThreadAbortException ex)
                {
                    Console.WriteLine("Alas, I was aborted!");
                    Thread.ResetAbort();
                    Console.WriteLine("But behold, I live!");
                }
            }
    }