我的代码在这里有什么问题? 即使items.count只有1,DoSomething方法会被调用两次,而计数器等于2.我没有正确地构造这些等待,还是我错误地使用了WhenAll?
public async Task<int> Process(string id) { var items = await GetItemsAsync(id); var counter = 0; var tasks = items.Select(async item => { if (await DoSomething(item)) counter++ }); if (tasks.Count() > 0) await Task.WhenAll(tasks); return counter; }What's wrong with my code here? Even when items.count is only 1, the DoSomething method gets called twice, and counter is equal to 2. Have I not structured the awaits correctly or am I using the WhenAll incorrectly?
public async Task<int> Process(string id) { var items = await GetItemsAsync(id); var counter = 0; var tasks = items.Select(async item => { if (await DoSomething(item)) counter++ }); if (tasks.Count() > 0) await Task.WhenAll(tasks); return counter; }最满意答案
基本上,您正在使用Select不正确。 这很懒,记得吗? 所以每次迭代它(一次为Count()和一次在WhenAll )...它将再次调用您的委托。
修复很简单:只需实现查询,例如使用ToList() :
var tasks = items.Select(async item => { if (await DoSomething(item)) { counter++ } }).ToList();这样你就可以创建一次任务。 实际上, tasks.Count()现在不需要迭代,因为它已经过优化以使用Count属性。 但是我仍然使用Any()来代替:
if (tasks.Any()) { await Task.WhenAll(tasks); }(顺便提一下,我总是强烈建议使用大括号,它更加抗错误...)
You're using Select incorrectly, basically. It's lazy, remember? So every time you iterate over it (once for Count() and once in WhenAll)... it's going to call your delegate again.
The fix is simple: just materialize the query, e.g. with ToList():
var tasks = items.Select(async item => { if (await DoSomething(item)) { counter++ } }).ToList();That way you create the tasks once. In fact, tasks.Count() doesn't need to iterate at all now, as it's optimized to use the Count property. But I'd still use Any() instead:
if (tasks.Any()) { await Task.WhenAll(tasks); }(I'd strongly advise always using braces, by the way. It's much more bug-resistant...)
更多推荐
发布评论