I'm trying to untangle this async behavior. Given this code:
static async Task Main(string[] args)
{
var cts = new CancellationTokenSource(4000);
try
{
await DoOperationAsync(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine
($"Operation canceled prematurely at {DateTime.Now}");
}
Console.WriteLine("Press any key...");
Console.ReadKey(true);
}
static async Task DoOperationAsync
(CancellationToken cancellationToken)
{
var t1 = Method("one", 5000, cancellationToken);
var t2 = Method("two", 5000, cancellationToken);
var first = await Task.WhenAny(t1, t2);
Console.WriteLine
($"Finished first: {(first == t2 ? "two" : "one")}, {first.Status}");
var result = await first;
}
static async Task<string> Method
(string name, int delayMs,
CancellationToken cancellationToken)
{
Console.WriteLine($"Started method {name} at {DateTime.Now}");
await Task.Delay(delayMs, cancellationToken);
Console.WriteLine($"Finished method {name} at {DateTime.Now}");
return name;
}
Why does "two" get canceled and "complete" first even though it started second, and then why does "one" never fault?
Here is the output:
Started method one at 2022-09-01 09:02:43
Started method two at 2022-09-01 09:02:43
Finished first: two, Canceled
Operation canceled prematurely at 2022-09-01 09:02:47
Press any key...
Finished method one at 2022-09-01 09:02:48