Await list of async predicates, but drop out on first false

后端 未结 6 1089
孤街浪徒
孤街浪徒 2021-01-12 21:20

Imagine the following class:

public class Checker
{
   public async Task Check() { ... }
}

Now, imagine a list of instances of

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-12 21:36

    All wasn't built with async in mind (like all LINQ), so you would need to implement that yourself:

    async Task CheckAll()
    {
        foreach(var checker in checkers)
        {
            if (!await checker.Check())
            {
                return false;
            }
        }
    
        return true;
    }
    

    You could make it more reusable with a generic extension method:

    public static async Task AllAsync(this IEnumerable source, Func> predicate)
    {
        foreach (var item in source)
        {
            if (!await predicate(item))
            {
                return false;
            }
        }
    
        return true;
    }
    

    And use it like this:

    var result = await checkers.AllAsync(c => c.Check());
    

提交回复
热议问题