Reputation: 38455
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
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
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