Handling Exception in Tpl

I read a lot about how to handle exceptions in TPL, but I don't understand.

Let's take this code example:

var task1 = new Task(() => { throw new Exception("Throw 1"); }); var task2 = task1.ContinueWith(t => Console.WriteLine("Catch 1:{0}", t.Exception.Message), TaskContinuationOptions.OnlyOnFaulted); var task3 = task2.ContinueWith(t => Console.WriteLine("Continuation")); task1.Start(); try { task1.Wait(); } catch (Exception ex) { Console.WriteLine("Wait Exception: {0}", ex.Message); } 

I expected it to print

 Catch 1 Continuation 

But I get

 Catch 1 Continuation Wait Exception 

This means that the exception is still considered unhandled when the task completes, and the task finalizer ultimately crashes the application.

How to handle exception in continuation so that the finalizer does not select? At the same time, I want the task to remain in an error state, so moving the task to try / catch will not work.


It is assumed that I want to implement the async event pattern specified here here , but with error handling. My complete code is as follows

 public IAsyncResult Begin(AsyncCallback callback, object state, Action action) { var task1 = new Task(action); var task2 = task1.ContinueWith(t => HandleException(t.Exception), TaskContinuationOptions.OnlyOnFaulted); if (callback != null) { var task3 = task2.ContinueWith(t => callback(t), TaskScheduler.FromCurrentSynchronizationContext()); var task4 = task3.ContinueWith(t => HandleException(t.Exception), TaskContinuationOptions.OnlyOnFaulted); } task1.Start(); return task; } 
+6
source share
1 answer

You expect an unsuccessful task, and if you carefully read the documentation for Task.Wait , you will see that the wait will be canceled by the exception in this case.

But if you are waiting for your task3 , everything should work as expected.

Of course you should keep this in mind:

Using the OnlyOnFaulted option ensures that the Exception property in the antecedent is not null. You can use this property to catch an exception and see which exception caused the task to fail. If you did not access the Exception property, the exception will be processed without processing. In addition, if you try to access the result of a property of a task that was canceled or worked, a new exception will be raised.

(Link here )

And finally, another good source on How to handle task exceptions

Hope this helps.

+3
source

Source: https://habr.com/ru/post/912079/


All Articles