开发者

How should a Thread notify its parent that it ended unexpectedly

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 开发者_Go百科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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜