I want to create three tasks a,b,c and run in order a,b,c using task chaining by using Task.continueWith

Vishal2 Bansal 265 Reputation points
2024-02-09T07:49:07.54+00:00

Following is the code block:-

		public static async Task task1()
         {
            await Task.Delay(4000);
             Console.WriteLine("Task 1 completed");
             
         }
        public static async Task task2()
        {
            await Task.Delay(1000);
            
                Console.WriteLine("Task 2 completed");
        }
        public static async Task task3()
        {
            await Task.Delay(2000);
            
                Console.WriteLine("Task 3 completed");
            
        }
        static void Main(string[] args)
        {
            Task t = Task.Run(() => { });
            t = t.ContinueWith(t =>
            {
                task1();
            });
            t = t.ContinueWith(t =>
            {
                task2();
            });
            t = t.ContinueWith(t =>
            {
                task3();
            });
            Console.ReadLine();
        }

Current Output of Above Code:-

Task 2 completed
Task 3 completed
Task 1 completed

Expected Output(what i want) :-

Task 1 completed
Task 2 completed
Task 3 completed

Please help and point out any mistake if i am doing...

Developer technologies | .NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-02-09T08:02:43.8766667+00:00

    Hi @Vishal2 Bansal , Welcome to Microsoft Q&A,

    You call each task in the ContinueWith method, but you don't use await to wait for those tasks to complete. Therefore, the tasks are executed concurrently, causing the output to be in a different order than you expect.

    You could try the following code to get what you wanted.

    static void Main(string[] args)
    {
        Task t = Task.Run(() => { });
    
        t = t.ContinueWith(_ =>
        {
            return Task1();
        }).Unwrap();
    
        t = t.ContinueWith(_ =>
        {
            return Task2();
        }).Unwrap();
    
        t = t.ContinueWith(_ =>
        {
            return Task3();
        }).Unwrap();
    
        t.Wait(); 
    
        Console.ReadLine();
    }
    

    Use the ContinueWith method to ensure that each task starts executing after the previous task completes. Use the Unwrap method to flatten nested tasks (since ContinueWith returns a Task<Task>). Finally, call the Wait method to wait for all tasks to complete.

    Or

     static async Task Main(string[] args)
        {
            await Task1();
            await Task2();
            await Task3();
            Console.ReadLine();
        }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.