CKTIS / C#
Task.WhenAny: praktična referenca
Task.WhenAny: praktična referenca: Task.WhenAny se konča, ko prvo opravilo doseže končno stanje, in vrne ta Task.
Različica: .NET API; verified against .NET 10 reference surface
Sintaksa
Task.WhenAny(/* overload-specific arguments */)Task.WhenAny se konča, ko prvo opravilo doseže končno stanje, in vrne ta Task.
Uporabite za tekmo operacij, nato awaitajte vrnjeni Task za rezultat ali napako.
Izgubljena opravila tečejo naprej; njihove izjeme je treba opazovati ali jih preklicati.
Prazna zbirka sproži ArgumentException; prvi zaključek je lahko faulted ali canceled.
Celoten program dejansko uporabi Task.WhenAny; natančno pričakovani stdout je first.
Primeri
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));
Rezultat
first
Celoten program dejansko uporabi `Task.WhenAny`; natančno pričakovani stdout je `first`.