Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return true when first async method returns true

Lets say i have the following code

public async Task<bool> PingAddress(string ipAddress)
{
    return await DoSomeThing(10) || await DoSomeThing(11) || await DoSomeThing(12);

}

private async Task<bool> DoSomeThing(int input)
{
    //Do some thing and return true or false.
}

How would i convert the return await DoSomeThing(10) || await DoSomeThing(11) || await DoSomeThing(12); to run in parallel and return true when first returns true and if all return false then return false!

like image 567
Peter Avatar asked Jun 11 '14 18:06

Peter


1 Answers

Here is an asynchronous "Any" operation on a collection of tasks.

public static async Task<bool> LogicalAny(this IEnumerable<Task<bool>> tasks)
{
    var remainingTasks = new HashSet<Task<bool>>(tasks);
    while (remainingTasks.Any())
    {
        var next = await Task.WhenAny(remainingTasks);
        if (next.Result)
            return true;
        remainingTasks.Remove(next);
    }
    return false;
}
like image 57
Servy Avatar answered Sep 21 '22 12:09

Servy