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

时间:2012-02-10 01:50:48

标签: c# .net multithreading

我停止使用.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!");

提前致谢。

1 个答案:

答案 0 :(得分:1)

您尝试中止的帖子中发生了什么?例如,这很好用:

    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,然后自己调用ResetAbort:

    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!");
                }
            }
    }