简体   繁体   中英

Tpl's Continuations and exceptions?

If I have a task which throws an exception , I can check in the continuation if there was an exception:

Task task1 = Task.Factory.StartNew (() => { throw null; });
Task task2 = task1.ContinueWith (ant => Console.Write (ant.Exception));

But I also know that :

If an antecedent throws and the continuation fails to query the antecedent's Exception property (and the antecedent isn't otherwise waited upon), the exception is considered unhandled and the application dies .

So I tried :

Task task1 = Task.Factory.StartNew (() => { throw null; });
Task task2 = task1.ContinueWith (ant => Console.Write (1));//1

But the application didn't crash.

Please, What am I missing ?

There are few different things going on:

First, if you call Wait() on a faulted Task , it will always throw an exception, no matter if you already observed it or not. In your code, this means that if you call task.Wait() from Main() , the whole application will crash, because you have unhandled exception in Main() .

Second, the behavior of unhandled exceptions in Task s changed in .Net 4.5 and they will no longer cause the application to crash. The article also describes how to switch back to the original behavior. And if you have .Net 4.5 installed, this applies also to applications targeting .Net 4.0 (eg those built using VS 2010).

Third, with the .net 4.0 behavior, the application crashes when the Task is garbage collected (assuming the exception wasn't observed before that point). This is because before that, there is still a chance your code will observe that exception.

So, the following code crashes the application (assuming you enabled the .Net 4.0 behavior if you have .Net 4.5 installed):

static void Main()
{
    Task.Factory.StartNew(() => { throw new Exception(); });

    // give the Task some time to run
    Thread.Sleep(100);

    GC.Collect();
}

Your code didn't crash, because the GC didn't have chance to run before the application exited normally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM