SoFunction
Updated on 2025-03-07

Example of continuous task usage in C#

Tasks allow you to specify that after the task is completed, another specific task should start running. For example, a new task that uses the results of the previous task, if the previous task fails, the task should perform some cleaning work. The task handler does not contain parameters or an object parameter, while the continuous processing method of the task has a Task type parameter. Here you can access the relevant information about the starting task:

As shown in the following example code:

   class Program
    {
        static void DoOnFirst()
        {
            ($"doing some task{}");
            (3000);
        }
        static void DoOnSecond(Task t)
        {
            ($"task {} finished");
            ($"this task id {}");
            ("doing some cleanup");
            (3000);
        }
        static void Main(string[] args)
        {
            Task t1 = new Task(DoOnFirst);
            ();
            

            Task t2 = (DoOnSecond);
            Task t3 = (DoOnSecond);
            Task t4 = (DoOnSecond);
            ();
        }
    }
 

Continuous tasks are defined by calling the ContinueWith() method on the task. You can also use the TaskFactory class to define. The (DoOnSecond) method means that a new task calling the DoOnSecond() method should be started immediately at the end of task t1. At the end of a task, multiple tasks can be started, and a continuous task can also have another continuous task. As shown in the following example:

            Task t1 = new Task(DoOnFirst);
            ();            

            Task t2 = (DoOnSecond);
            Task t3 = (DoOnSecond);
            Task t4 = (DoOnSecond);

Using the values ​​in the TaskCreationOptions enumeration, you can specify that consecutive tasks can only be started when the initial task is successful (or failed). Some possible values ​​are OnlyOnFaulted, NotOnFaulted, OnlyOnCanceled, NotOnCanceled, and OnlyOnRanToCompletion.

Task t5 = (DoOnError, )

C# Return object

Use logic that can continue execution when the Task is completed

How should I use it when an object needs to be returned in ContinueWith

The code below can indicate that after setting the cache, re-read the cache and return it

 var item = await SetCacheItemAsync("key",  cacheItems)
                .ContinueWith<>(async _ => await (key));

This is the end of this article about continuous task usage examples in C#. For more related C# content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!