代码之家  ›  专栏  ›  技术社区  ›  Ralph Shillington

线程应该如何通知其父线程它意外结束

  •  0
  • Ralph Shillington  · 技术社区  · 14 年前

    我有一个线程正在监听套接字并转发它接收到的消息到处理引擎。如果发生了一些不好的事情(比如套接字意外关闭),线程应该如何通知它的“父”它即将结束?

    更新:例如,这里有一个简单的问题:

    class Program
        {
            private static BlockingCollection<string> queue = new BlockingCollection<string>();
            static void Main(string[] args)
            {
                Thread readingThread = new Thread(new ThreadStart(ReadingProcess));
                readingThread.Start();
                for (string input = queue.Take(); input != "end"; input = queue.Take())
                    Console.WriteLine(input);
                Console.WriteLine("Stopped Listening to the queue");
            }
            static void ReadingProcess()
            {
                string capture;
                while ((capture = Console.ReadLine()) != "quit")
                    queue.Add(capture);
                // Stop the processing because the reader has stopped.
            }
        }
    

    在本例中,Main在看到“end”时结束于for循环,或者读取过程在看到“quit”时结束。两个线程都被阻塞(一个在ReadLine上,另一个在Take上)。

    按照马丁的建议,阅读过程可能会添加到阻塞队列和“结束”--不过,队列中可能还有其他东西在这个毒丸前面,在这个阶段,我希望队列立即停止。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Martin v. Löwis    14 年前

    使用相同的机制,它将请求转发到处理引擎:有一个特殊的“错误请求”指示线程已终止。

    或者,使用EventWaitHandle,让父线程等待任何子线程发出意外终止的信号。

        2
  •  1
  •   Henk Holterman    14 年前

    不要让父线程负责。停止线程可以自己进行清理等,并在需要时向中心对象(侦听器管理器)报告。