none
Why the thread isn't invoked? RRS feed

  • Question

  • class Program
        {
            static  Task Fun()
            {
                return Task.Factory.StartNew(() => 
                {
                    throw new Exception("Error……");
                });
            }
            static void Main(string[] args)
            {
                var t = Fun();
                Console.ReadLine();
            }
        }
    I've used Console.ReadLine() to hold the main UI thread, and the background thread of Task should be invoked……But in fact it isn't ……Why?!Why isn't the Exception thrown out?
    • Edited by TimoYang Thursday, August 23, 2012 9:08 AM
    Thursday, August 23, 2012 9:04 AM

Answers

  • I've used Console.ReadLine() to hold the main UI thread, and the background thread of Task should be invoked……But in fact it isn't ……Why?!Why isn't the Exception thrown out?

    What makes you think that the thread isn't started?  Set a breakpoint on the throw and you'll see that the task does run in a new thread.

    Why aren't you seeing an exception?  Because unhandled exceptions from Tasks are queued in the Task object and will be raised in your thread when you call Wait() (or a variety of other circumstances).

    Try adding a call to t.Wait() after your ReadLine and see what happens.


    -cd Mark the best replies as answers!

    • Proposed as answer by Chris Wigley Saturday, August 25, 2012 8:57 PM
    • Marked as answer by TimoYang Sunday, August 26, 2012 3:29 AM
    Friday, August 24, 2012 4:02 PM
    Moderator

All replies