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; }
source share