Wait for first task in array to match a condition

I have a Task<bool>[] myTasks. How do I get notified (await) when the first Task returns true ?

Jon Skeet
people
quotationmark

Basically, you need to keep a set of incomplete tasks, and repeatedly use Task.WhenAny, check the result, and keep going (having removed that task) if the result wasn't what you were looking for. For example:

ISet<Task<bool>> activeTasks = new HashSet<Task<bool>>(myTasks);
while (activeTasks.Count > 0)
{
    Task<bool> completed = await Task.WhenAny(activeTasks);
    if (completed.Status == TaskStatus.RanToCompletion &&
        completed.Result)
    {
        // Or take whatever action you want
        return;
    }
    // Task was faulted, cancelled, or had a result of false.
    // Go round again.
    activeTasks.Remove(completed);
}
// No successful tasks - do whatever you need to here.

people

See more on this question at Stackoverflow