Posts

....
Technical Blog for .NET Developers ©

Tuesday, July 23, 2019

Threading : Implementation of ContinueWith()

In Threading tasks can be ordered to run consecutively with the implementations of ContinueWith methods

In this post we implement examples of this method and make a review of the options enumerated in TaskContinuationOptions. With three examples of continuation and its options

Consider this code: (notice the commented lines to make functions 3 and 4 run)


        static void TasksContinuationsDemo()
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();

            CancellationToken token = tokenSource.Token;

            token.Register(() =>
            {
                Console.WriteLine("Cancelation's been requested");
            });

            Task<bool> initialTask = new Task<bool>(() => 
            {
                Console.WriteLine("Tasks continuation demo");

                token.ThrowIfCancellationRequested();

                // OnlyOnFaulted option
                // throw new Exception();

                Console.WriteLine(true);

                return true;
            }, 
            token);

            Task task2 = initialTask.ContinueWith(result =>
            {
                Console.WriteLine("Initial Task ran to completion");

                Console.WriteLine("Initial Task result is {0}", result.Result);

            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            Task<int> task3 = initialTask.ContinueWith<int>(result =>
            {
                Console.WriteLine("Initial task faulted");

                Console.WriteLine("Task 3 result is {0}", 1);

                return 1;

            }, TaskContinuationOptions.OnlyOnFaulted);

            Task<bool> task4 = initialTask.ContinueWith<bool>(result =>
            {
                Console.WriteLine("Initial Task's been canceled");

                Console.WriteLine("Task 4 result is {0}", true);

                return true;

            }, TaskContinuationOptions.OnlyOnCanceled);

            initialTask.Start();

            // OnlyOnCanceled option
            // tokenSource.Cancel();
        }


With this result:



Now uncomment the //OnlyOnFaulted option

With the next result:



And now uncomment the //OnlyOnCanceled option

With the next result:



The enum TaskContinuationOptions presents these options:



MSDN