c# - 当第一个异步方法返回 true 时返回 true

标签 c# .net asynchronous task-parallel-library

假设我有以下代码

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

我将如何转换 return await DoSomeThing(10) ||等待 DoSomeThing(11) || await DoSomeThing(12); 并行运行并在第一次返回 true 时返回 true,如果全部返回 false 则返回 false!

最佳答案

这是对任务集合的异步“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;
}

关于c# - 当第一个异步方法返回 true 时返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24169593/

相关文章:

c# - 我应该使用什么样的数据结构?

c# - 如何将参数和上传图片同时传递给 One web api?

node.js - 我应该异步将数据保存到数据库吗

python - 什么时候不使用 asyncio 有意义?

c# - 动态 LINQ where 查询

c# - 更正 EventHandler 以在记事本关闭时告诉我

c# - 如何解析由 WebBrowser 控件加载的 HTML 文件中的图像

.net - 为产品的多个版本开发代码库

c# - 在 C# 中同步包装异步方法

C# 窗体 : Control locked but locked propety is set to false