CKTIS / C#
Task.WhenAny: practical reference
Task.WhenAny: practical reference: Task.WhenAny completes when the first task reaches a terminal state and returns that Task.
Version: .NET API; verified against .NET 10 reference surface
Syntax
Task.WhenAny(/* overload-specific arguments */)Task.WhenAny completes when the first task reaches a terminal state and returns that Task.
Use it to race operations, then await the returned Task to observe its result or failure.
Losing tasks keep running; their exceptions must be observed or they must be canceled.
An empty collection throws ArgumentException; the first completion may be faulted or canceled.
The complete program actually uses Task.WhenAny; its exact expected stdout is first.
Examples
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;
var first = Task.FromResult("first");
var second = new TaskCompletionSource<string>().Task;
Console.WriteLine(await await Task.WhenAny(first, second));
Result
first
The complete program actually uses `Task.WhenAny`; its exact expected stdout is `first`.