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.