Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for first task in array to match a condition

Tags:

c#

async-await

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

like image 736
Milleu Avatar asked Nov 16 '16 07:11

Milleu


1 Answers

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.
like image 85
Jon Skeet Avatar answered Sep 19 '22 04:09

Jon Skeet