使用Async指向List< T> .ForEach()吗? [英] Any point to List<T>.ForEach() with Async?

查看:85
本文介绍了使用Async指向List< T> .ForEach()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这段代码:

items.ForEach(async item =>
{
     doSomeStuff();   
     await mongoItems.FindOneAndUpdateAsync(mongoMumboJumbo);
     await AddBlah(SqlMumboJumbo);
});

将其设置为.forEach委托是否有任何意义,还是只是普通的foreach循环?只要包含循环的函数处于异步状态,默认情况下这将是异步状态?

Is there any point in making this a .forEach delegate, or could it be just a normal foreach loop? As long as the function that contains the loop is in is async, this would be async by default?

推荐答案

ForEach收到的委托是Action<T>:

public void ForEach(Action<T> action)

这意味着,您在其中使用的任何异步委托都将有效地转换为async void方法.这些是执行忘却"的风格.这意味着您的foreach在继续调用列表中下一项上的委托之前,不会异步完成等待,这可能是不希望的行为.

This means, that any async delegate you use inside it will effectively turn into an async void method. These are "fire and forget" style of execution. This means your foreach wont finish asynchronously waiting before continuing to invoke the delegate on the next item in the list, which might be an undesired behavior.

改为使用常规的foreach.

旁注- foreach VS埃里克·利珀特(Eric Lippert)撰写的ForEach ,精彩的博客文章.

Side note - foreach VS ForEach by Eric Lippert, great blog post.

这篇关于使用Async指向List&lt; T&gt; .ForEach()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆