Chaining Tasks by Using Continuation Tasks

Chaining Tasks by Using Continuation Tasks in C#

In this article, I am going to discuss how to Chaining Tasks by Using Continuation Tasks in C# with some examples. Please read our previous article where we discussed How to Return a Value from a Task in C# with some examples.

While working with asynchronous programming, it is very common to invoke one asynchronous operation from another asynchronous operation passing the data once it completes its execution. This is called as continuations and in the traditional approach, this has been done by using the callback methods which is little difficult to understand.

But with the introduction of Task Parallel Library (TPL), the same functionality can be achieved very easily by using continuation tasks. In simple words, we can define a continuation task as an asynchronous task which is going to be invoked by another task (i.e. known as the antecedent).

Creating a continuation for a single antecedent

In C#, you can create a continuation by calling the ContinueWith method that is going to execute when its antecedent has completed its execution.

In the following example, the antecedent task i.e. task1 return an integer value. When it completes its executions, then it passes that value to the continuation task and that continuation task does some operation and returns the result as a string.

using System;
using System.Threading.Tasks;

namespace TaskBasedAsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<string> task1 = Task.Run(() =>
            {
                return 12;
            }).ContinueWith((antecedent) =>
            {
                return $"The Square of {antecedent.Result} is: {antecedent.Result * antecedent.Result}";
            });
            Console.WriteLine(task1.Result);
            
            Console.ReadKey();
        }
    }
}

Output: The Square of 12 is : 144

Scheduling Different Continuation Tasks

The ContinueWith method has some overloaded versions that you can use to configure with multiple options when the continuation will run. In this way, you can add different continuation methods that will run when an exception occurred, when the Task is canceled, or the Task completed successfully. Let us see an example to understand this.

using System;
using System.Threading.Tasks;

namespace TaskBasedAsynchronousProgramming
{
    class Program
    {
        static void Main(string[] args)
        {
            Task<int> task = Task.Run(() =>
            {
                return 10;
            });

            task.ContinueWith((i) =>
            {
                Console.WriteLine("TasK Canceled");
            }, TaskContinuationOptions.OnlyOnCanceled);

            task.ContinueWith((i) =>
            {
                Console.WriteLine("Task Faulted");
            }, TaskContinuationOptions.OnlyOnFaulted);


            var completedTask = task.ContinueWith((i) =>
            {
                Console.WriteLine("Task Completed");
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            completedTask.Wait();

            Console.ReadKey();
        }
    }
}

That’s it for today. In the next article, I am going to discuss how to attached child task to a parent task in C# with some examples. In this article, I try to explain how to Chaining Tasks by Using Continuation Tasks in C# with some examples. I hope you enjoy this article.

1 thought on “Chaining Tasks by Using Continuation Tasks”

Leave a Reply

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