I'd like to make a request to X different web services who will each return either true
or false
.
These tasks should be executed in parallel and I'd like to wait for the first one that completes with a true value. When I receive a true value, I do not wish to wait for the other tasks to complete.
In the example below, t1
should not be awaited since t3
completes first and returns true
:
var t1 = Task.Run<bool>(() =>
{
Thread.Sleep(5000);
Console.WriteLine("Task 1 Excecuted");
return true;
}, cts.Token);
var t2 = Task.Run<bool>(() =>
{
Console.WriteLine("Task 2 Executed");
return false;
}, cts.Token);
var t3 = Task.Run<bool>(() =>
{
Thread.Sleep(2000);
Console.WriteLine("Task 3 Executed");
return true;
}, cts.Token);
Essentially I'm looking for Task.WhenAny
with a predicate, which of course doesn't exist.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…