c# - 避免在 foreach 循环中等待

标签 c# .net performance async-await

我正在尝试优化此代码以减少完成 for 循环所需的时间。在这种情况下,CreateNotification() 需要很长时间,并且使用 async await 不会提高性能,因为正在等待每个异步调用。我想使用 Task.WhenAll() 来优化代码。我怎样才能做到这一点?

foreach (var notification in notificationsInput.Notifications)
{
  try
  {
    var result = await CreateNotification(notification);
    notification.Result = result;          
  }
  catch (Exception exception)
  {
    notification.Result = null;
  }
  notifications.Add(notification);
}

最佳答案

您可以在要并行处理其元素的集合上调用 Select,将异步委托(delegate)传递给它。此异步委托(delegate)将为每个已处理的元素返回一个 Task,因此您可以在所有这些任务上调用 Task.WhenAll。模式是这样的:

var tasks = collection.Select(async (x) => await ProcessAsync(x));
await Task.WhenAll(tasks);

你的例子:

var tasks = notificationsInput.Notifications.Select(async (notification) =>
{
    try
    {
        var result = await CreateNotification(notification);
        notification.Result = result;          
    }
    catch (Exception exception)
    {
        notification.Result = null;
    }
});
await Task.WhenAll(tasks);

这假设 CreateNotification 是线程安全的。

关于c# - 避免在 foreach 循环中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893933/

相关文章:

java - 自定义脚本编辑器

MYSQL - 分页查询执行时间问题

c# - Microsoft Speech Platform Runtime 11 和 Cortana 的语音识别有区别吗?

c# - 从程序集中强制卸载 DLL

c# - 注册表和注册表配置单元有什么区别

c# - 如何正确使用TransactionScope?

c# - 从字符串变量中的名称创建类的对象实例

c# - 我在哪里放置 try/catch with "using"语句?

.net - .NET 和 ASP.NET 有什么区别

c# - 对于已知情况是否应该避免 try catch