问题描述:

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

网友答案:

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.
相关阅读:
Top