How to properly manage exception in task with ContinueWith

After reading the information about task management and exepcion, I use this code to control the exception created in the Task:

Task<Object> myTask = Task.Factory.StartNew<Object>(doTask, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); myTask .ContinueWith(task => afterTask(task), TaskScheduler.FromCurrentSynchronizationContext()); 

Where doTask and AfterTask:

 private <Object> doTask() { throw new Exception("BOOM"); } private afterTask(Task<Object> aTask) { if (aTask.IsFaulted) { MessageBox.Show(aTask.Exception.InnerException.Message); } else //whatever } 

When an Exception Boom is raised, Visual Studio displays a warning warning that no exception has been detected, but if I continue to throw an exception, the afterTask function is processed.

Is this code correct, or am I missing some basic task behavior? Is there a way to avoid a warning from the debugger that it could not be caught? This is a little annoying ...

Thanks in advance

+7
multithreading c # exception task
source share
2 answers

Try this instead:

  task.ContinueWith( t => t.Exception.Handle(ex => { logger.Error(ex.Message, ex); return false; }) , TaskContinuationOptions.OnlyOnFaulted ); 

Using TaskContinuationOptions.OnlyOnFaulted , you will only run your ContinueWith block if the original task was selected due to an exception.

In addition, you can choose whether to return true or false from the lambda passed to Handle , indicating whether the exception was handled or not. In my case, I did not want to stop distributing the exception. You can change it to return true in your case.

+21
source share
  try { var t1 = Task.Delay(1000); var t2 = t1.ContinueWith(t => { Console.WriteLine("task 2"); throw new Exception("task 2 error"); }, TaskContinuationOptions.OnlyOnRanToCompletion); var t3 = t2.ContinueWith(_ => { Console.WriteLine("task 3"); return Task.Delay(1000); }, TaskContinuationOptions.OnlyOnRanToCompletion).Unwrap(); // The key is to await for ALL tasks rather than just // the first or last task. await Task.WhenAll(t1, t2, t3); } catch (AggregateException aex) { aex.Flatten().Handle(ex => { // handle your exceptions here Console.WriteLine(ex.Message); return true; }); } 
-3
source share

All Articles