Sobes.tech
Junior — Middle

How do the methods WaitAll and WhenAll differ in asynchronous programming?

sobes.tech AI

Answer from AI

The methods WaitAll and WhenAll in C# are used to wait for the completion of multiple tasks but have important differences:

  • WaitAll is a synchronous method from the Task class that blocks the current thread until all the provided tasks are completed. It does not return a result and does not support asynchronous waiting.

  • WhenAll is an asynchronous method that returns a task which completes when all the provided tasks are finished. It allows using await for non-blocking waiting, which improves application performance and responsiveness.

Example of using WhenAll:

var tasks = new[] { Task.Delay(1000), Task.Delay(2000) };
await Task.WhenAll(tasks);
Console.WriteLine("All tasks are completed");

Using WaitAll:

var tasks = new[] { Task.Delay(1000), Task.Delay(2000) };
Task.WaitAll(tasks);
Console.WriteLine("All tasks are completed");

The main difference is that WaitAll blocks the thread, while WhenAll allows asynchronous waiting without blocking.