想象一下下面的类:
公共类检查
{
公共异步任务<布尔>检查(){...}
}
现在,想象一下这个类的实例列表:
的IEnumerable<检查>跳棋= ...
现在我想控制每个实例将返回真
:
checkers.All(C => c.Check());
现在,这不会编译,因为检查()
返回任务<布尔>
不是布尔
。
所以我的问题是:我怎样才能最好的枚举检查器列表中?
我怎样才能尽快快捷枚举作为检查返回假
?
(这是我presume 所有()
做的话)
和我怎么能快捷枚举只要一检查返回false?
这将为了完成检查任务的结果。因此,如果任务#5是第一个完成,并返回false,该方法将立即返回false,不管其他任务。较慢的任务(#1,#2,等)将永远不会被检查。
公共静态异步任务<布尔> AllAsync(这IEnumerable的<任务<布尔>>源)
{
变种任务= source.ToList();
而(tasks.Count!= 0)
{
VAR finishedTask =等待Task.WhenAny(任务);
如果(!finishedTask.Result)
返回false;
tasks.Remove(finishedTask);
}
返回true;
}
用法:
布尔结果=等待checkers.Select(C => c.Check())
.AllAsync();
Imagine the following class:
public class Checker
{
public async Task<bool> Check() { ... }
}
Now, imagine a list of instances of this class:
IEnumerable<Checker> checkers = ...
Now I want to control that every instance will return true
:
checkers.All(c => c.Check());
Now, this won't compile, since Check()
returns a Task<bool>
not a bool
.
So my question is: How can I best enumerate the list of checkers?
And how can I shortcut the enumeration as soon as a checker returns false
?
(something I presume All( )
does already)
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<bool> AllAsync(this IEnumerable<Task<bool>> 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();