避免在 foreach 循环中等待

Aji*_*oel 3 .net c# 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);
}
Run Code Online (Sandbox Code Playgroud)

Dou*_*las 7

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

var tasks = collection.Select(async (x) => await ProcessAsync(x));
await Task.WhenAll(tasks);
Run Code Online (Sandbox Code Playgroud)

对于您的示例:

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);
Run Code Online (Sandbox Code Playgroud)

这假设它CreateNotification是线程安全的。