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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With