【发布时间】:2018-06-17 05:21:06
【问题描述】:
我正在尝试优化此代码以减少完成forloop 所需的时间。在这种情况下,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);
}
【问题讨论】:
-
你的 CreatNotification 做什么以及
context是什么 -
你可以改用Parallel.ForEach。
-
CreateNotification 是一个 lambda 函数。 CreateNotification 调用端点来创建通知。我已经编辑了代码以删除上下文
-
@Leandro 这与异步方法的配合不太好:)
标签: c# .net performance async-await