CKTIS / C#
Task — asynchronous operations and waiting for groups of tasks
Task represents an asynchronous operation, while Task<T> also provides its result. Learn the differences between Task.Yield, blocking Task.WaitAll, and nonblocking Task.WhenAll, including result ordering and failure handling.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
await Task.Yield();
Task.WaitAll(tasks);
Task combined = Task.WhenAll(tasks);
TResult[] results = await Task.WhenAll<TResult>(resultTasks);System.Threading.Tasks.Task represents an asynchronous operation without a result value; Task<T> provides a result of type T. A task is not the same thing as a thread. The calls described here are available in .NET 10 and require no preview language features.
await Task.Yield() forces asynchronous resumption of the remainder of the method. The Task.Yield() call returns YieldAwaitable, not Task; the full await Task.Yield() expression produces no value. The continuation is posted to the current synchronization context if it is an instance of a type derived from SynchronizationContext. If there is no current context or its type is exactly SynchronizationContext, the current task scheduler is used instead. This guarantees neither a thread switch nor a responsive user interface.
Task.WaitAll(tasks) blocks the calling thread until all tasks finish. It reports task failures or cancellation through AggregateException. Blocking a thread needed by continuations can cause deadlock; prefer await Task.WhenAll(tasks) in asynchronous code. Canceling the wait itself through a token overload does not cancel the tasks.
Task.WhenAll(tasks) returns a combined task without blocking the calling thread. For Task<T>[], the awaited result is an array in input order, not completion order. Any task failure produces Faulted; with no failures but some cancellation, the state is Canceled; otherwise it succeeds. Empty input succeeds immediately. The example prints results only after await; Task.WaitAll is demonstrated solely with already completed tasks.
Examples
using System;
using System.Threading.Tasks;
internal static class Program
{
private static async Task Main()
{
Task<int>[] tasks = { DoubleAsync(3), DoubleAsync(5) };
int[] results = await Task.WhenAll(tasks);
Console.WriteLine(string.Join(", ", results));
Task[] completed = { Task.CompletedTask, Task.CompletedTask };
Task.WaitAll(completed);
Console.WriteLine("WaitAll completed");
}
private static async Task<int> DoubleAsync(int value)
{
await Task.Yield();
return value * 2;
}
}Result
6, 10 WaitAll completed
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.