Peter
Peter

Reputation: 38455

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!

Upvotes: 8

Views: 2471

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564373

You can use await Task.WhenAny to determine when the tasks return, and return true when the first one completes.

This typically looks like:

var tasks = new List<Task<bool>> 
                {
                   DoSomething(10), 
                   DoSomething(11), 
                   DoSomething(12)                        
                };

while (tasks.Any())
{
     var t = await Task.WhenAny(tasks);
     if (t.Result) return true;

     tasks.Remove(t);
}

// If you get here, all the tasks returned false...

Upvotes: 5

Servy
Servy

Reputation: 203821

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;
}

Upvotes: 10

Sean Barlow
Sean Barlow

Reputation: 588

You need to use a WaitHandle. Take a look at MSDN

Upvotes: -3

Related Questions