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

后端 未结 6 893
孤街浪徒
孤街浪徒 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:51

    And how can I shortcut the enumeration as soon as a checker returns false?

    This will check the tasks' result in order of completion. So if task #5 is the first to complete, and returns false, the method returns false immediately, regardless of the other tasks. Slower tasks (#1, #2, etc) would never be checked.

    public static async Task AllAsync(this IEnumerable> source)
    {
        var tasks = source.ToList();
    
        while(tasks.Count != 0)
        {
            var finishedTask = await Task.WhenAny(tasks);
    
            if(! finishedTask.Result)
                return false;
    
            tasks.Remove(finishedTask);
        }
    
        return true;
    }
    

    Usage:

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

提交回复
热议问题