C#C
C#17mo ago
Shinigami

Why does Task 1 prints first instead of Task 3 - Async & Await

internal class Program
    {
        private static async Task Main(string[] args)
        {
            Task firstTask = Task.Run(async ()=> {
                // Thread.Sleep(1000);
                await Task.Delay(10000);
                Console.WriteLine("Task 1");
            });
            // firstTask.Start();
            // Console.WriteLine("YOYOYOY");
            await firstTask;

            Task secondTask = ConsoleWithDelayAsync("Task 2",150);
            Task thirdTask = ConsoleWithDelayAsync("Task 3",9);
            Task fourthTask = ConsoleWithDelayAsync("Task 4",80);

            await secondTask;
            await thirdTask;
            await fourthTask;
        }

        public static void ConsoleWithDelay(string text, int delay){
            Thread.Sleep(delay);
            Console.WriteLine(text);
        }

        public static async Task ConsoleWithDelayAsync(string text, int delay){
            await Task.Delay(delay);
            Console.WriteLine(text);
        }
    }


The output I'm getting is

Task 1
Task 3
Task 4
Task 2

Aren't all the Tasks async above? So while Task 1 waits for 10 secs should the rest of the code continue?
Was this page helpful?