How should a Thread notify its parent that it ended unexpectedly

◇◆丶佛笑我妖孽 提交于 2019-12-25 09:31:01

问题


I have a thread that is listening on a socket and forwarding on the messages it receives to processing engine. If something untoward happen (such as the socket is unexpectedly closed) how should that thread notify it's "parent" that it's about to end?

UPDATE: For example, here's a simple illistration of the issue:

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.
        }
    }

In this example, either the Main finishes out of the for loop when it sees "end" or the reading process finishes because it sees "quit". Both threads are blocked (one on a ReadLine, and the other on a Take.

Following Martin's advice the ReadingProcess could add to the BlockingQueue and "end" --- however there may be other things ahead of this poison pill in the queue, and at this stage I would like the queue to stop right away.


回答1:


Using the same mechanism it forwards the requests to the processing engine: have a special "error request" that indicates that the thread is terminated.

Alternatively, use an EventWaitHandle, and have the parent thread wait for any child signalling its unexpected termination.




回答2:


Don't make the parent-thread responsible. The stopping thread can do it's own cleanup etc and report to a central object (listener-manager) when that is required.



来源:https://stackoverflow.com/questions/4257427/how-should-a-thread-notify-its-parent-that-it-ended-unexpectedly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!