C#C
C#17mo ago
Robert

Skill issue serializing tasks

Hi!

I need to serialize a list of tasks to only begin when the previous task is fully completed, let's take this snippet for example
async Task TestAsync(string log)
        {
            Console.WriteLine($"delay start {log}");
            await Task.Delay(5000);
            Console.WriteLine($"delay   end {log}");
        }

        [TestMethod]
        public async Task TestTasks()
        {
            List<Task> tasks = new()
            {
                TestAsync("1"),
                TestAsync("2"),
                TestAsync("3"),
            };

            /*
            How do I achieve this?
            delay start 1
            delay  end 1
            delay start 2
            delay  end 2
            delay start 3
            delay  end 3
            */
        }


I've tried using Task.WaitAll, await Task.WhenAll, looping and awaiting them, continue with (with and without await), but the closest i've been to succes is
delay start 1
delay start 2
delay start 3
delay end 3
delay end 2
delay end 1

Thank you!
Was this page helpful?