CKTIS / C#
Task.WhenAny: praktická referencia
Task.WhenAny: praktická referencia: Task.WhenAny sa dokončí, keď prvá úloha dosiahne koncový stav, a vráti tento Task.
Verzia: .NET API; verified against .NET 10 reference surface
Syntax
Task.WhenAny(/* overload-specific arguments */)Task.WhenAny sa dokončí, keď prvá úloha dosiahne koncový stav, a vráti tento Task.
Použite na preteky operácií a vrátený Task potom awaitujte kvôli výsledku alebo chybe.
Prehrávajúce úlohy bežia ďalej; ich výnimky treba pozorovať alebo ich zrušiť.
Prázdna kolekcia vyhodí ArgumentException; prvé dokončenie môže byť faulted alebo canceled.
Úplný program skutočne používa Task.WhenAny; presne očakávaný stdout je first.
Príklady
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));
Výsledok
first
Úplný program skutočne používa `Task.WhenAny`; presne očakávaný stdout je `first`.