TPL exception handling

http://msdn.microsoft.com/en-us/library/dd997415.aspx

In the article mentioned above, I am trying to handle exceptions in the account assignment task. The example in the above article is as follows:

var task1 = Task.Factory.StartNew(() => { throw new MyCustomException("Task1 faulted."); }) .ContinueWith((t) => { Console.WriteLine("I have observed a {0}", t.Exception.InnerException.GetType().Name); }, TaskContinuationOptions.OnlyOnFaulted); 

My code is:

 Task<string> task = Task<string>.Factory.StartNew(() => process.StartTask(this)); task.ContinueWith(CloseDialog, TaskContinuationOptions.OnlyOnFaulted); 

In StartTask, I throw an error, as in the example. My expectation is that CloseDialog will execute, and I can check task.Exception in this method, as shown in the example. However, when I throw an exception, the code just stops with the unhandled exception. Should I use a try / catch block? If so, where? By the way, I want my continuation task (CloseDialog) to ALWAYS run. I just use .OnlyOnFaulted because this is what the example shows.

+7
source share
1 answer

A sequel can find out if an exception was created by the Task antecedent by the exception property of a previous task. The following prints the results of a NullReferenceException to the console

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

If task1 throws an exception, and this exception is not caught / not requested by the continuation, it is considered unhandled and the application dies. With the continuation, it is enough to set the result of the task using the Status keyword

 asyncTask.ContinueWith(task => { // Check task status. switch (task.Status) { // Handle any exceptions to prevent UnobservedTaskException. case TaskStatus.RanToCompletion: if (asyncTask.Result) { // Do stuff... } break; case TaskStatus.Faulted: if (task.Exception != null) mainForm.progressRightLabelText = task.Exception.InnerException.Message; else mainForm.progressRightLabelText = "Operation failed!"; default: break; } } 

If you do not use continuations, you need to either wait for the task to complete in the try / catch , or request the Result task in the try / catch

 int x = 0; Task<int> task = Task.Factory.StartNew (() => 7 / x); try { task.Wait(); // OR. int result = task.Result; } catch (AggregateException aggEx) { Console.WriteLine(aggEx.InnerException.Message); } 

I hope for this help, even if it's a little late, and you all know what it is !:]

+10
source

All Articles