好吧,您可以调用Save()
所有内容,然后等待所有内容完成使用Task.WhenAll
:
public async Task Save()
{
await Task.WhenAll(Elements.Select(x => x.Save());
}
或者,如果您真的什么都不做,只需:
public Task Save()
{
return Task.WhenAll(Elements.Select(x => x.Save());
}
编辑:如果您想连续执行它们,请使用您已经获得的代码。值得注意的是,异步/等待的设计方式,等待实际上同步完成的调用(例如缓存命中,或者在您的情况下是脏检查)非常便宜。它不需要做任何任务调度、创建延续或类似的事情。你说:
如果我有一个包含 10000 个对象的列表,并且只有 1 个是脏的,我最终会得到 9999 个不必要的异步等待,我怀疑这会很重要。
As ever, suspicions about performance bottlenecks are pretty much meaningless - what's important is evidence about performance bottlenecks. Have you tried the existing code and measured the cost? If not, I strongly suggest you do that before changing anything.