[英]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);
我将如何转换return await DoSomeThing(10) || await DoSomeThing(11) || await DoSomeThing(12);
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! 并行运行并在第一次返回true时返回true,如果all返回false则返回false!
Here is an asynchronous "Any" operation on a collection of tasks. 这是对任务集合的异步“Any”操作。
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;
}
You can use await Task.WhenAny
to determine when the tasks return, and return true when the first one completes. 您可以使用await Task.WhenAny
来确定任务何时返回,并在第一个任务完成时返回true。
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...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.