即使只有一个项目,使用async / await和Task.WhenAll也会触发两个任务(Two tasks are firing even when there's only one i

编程入门 行业动态 更新时间:2024-10-26 19:35:47
即使只有一个项目,使用async / await和Task.WhenAll也会触发两个任务(Two tasks are firing even when there's only one item, using async/await and Task.WhenAll)

我的代码在这里有什么问题? 即使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...)

更多推荐

本文发布于:2023-04-27 11:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:也会   只有一个   两个   项目   await

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!