TPL wait for task to complete with a specific return value
.net, async-await, c#, task-parallel-library
Solution
You can simply use `Task.WhenAny` and a predicate multiple times until the "right" task comes along
async Task<T> WhenAny<T>(IEnumerable<Task<T>> tasks, Func<T, bool> predicate)
{
var taskList = tasks.ToList();
Task<T> completedTask = null;
do
{
completedTask = await Task.WhenAny(taskList);
taskList.Remove(completedTask);
} while (!predicate(await completedTask) && taskList.Any());
return completedTask == null ? default(T) : await completedTask;
}
Problem
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.