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 !:]
Moonknight
source share