C# Task.ContinueWith() method

We all worked with ContinueWith() method but there are some interesting and useful facts we should be aware of.

First of all lets remember what is Continuation regarding the Tasks. When we looking for this definition in MSDN , we see following:<

Creates a continuation that executes asynchronously when the target Task completes.


Lets see an example:

Task task1 = Task.Factory.StartNew(() => Console.Write ("creating first task));
Task task2 = task1.ContinueWith(Console.Write ("continue anyway"));

But actually there are few interesting facts 🙂
Fact 1: task1 and task2 in previous example may run on a different threads. In order to obligate to  run on the same thread we can use TaskContinuationOptions.ExecuteSynchronously.
Fact 2: Its important to know that ContinueWith()  method will be executed anyway, whenever Task succeeded, faulted or canceled. It give us great opportunity to deal sometimes with different cases accordingly: in case of exceptions do this and in case of success do that. We can achieve it like this:

Task someTask= Task.Factory.StartNew (() => { throw new Exception(); });
 
Task exceptions= someTask.ContinueWith (ant => Console.Write (ant.Exception),
                                 TaskContinuationOptions.OnlyOnFaulted);
 
Task noExceptions = task1.ContinueWith (ant => Console.Write("No Exceptions!"),TaskContinuationOptions.NotOnFaulted);

Have a great coding time 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *