【问题标题】:Task WhenAll with multiple taks that all have their own tasksTask WhenAll 具有多个任务,它们都有自己的任务
【发布时间】:2016-04-09 07:00:47
【问题描述】:

我想调用 Task.WhenAll 并等待一些任务,每个任务都有自己的子任务,我想知道我在我的实现中是否正确地执行了它,这似乎有点冗长,我想知道是否它有一个更短的版本。

public async Task ChangeNotificationsDispatchTimeAsync(string userId, DateTime utcDateTimeToSend)
{
    IList<TNotificationEntity> notifications =
        await _notificationsTable.GetRowsByPartitionKeyAndRowKeyAsync(ToTicks(_now), userId, QueryComparisons.GreaterThanOrEqual);
    await Task.WhenAll(
        notifications.Select(notification =>
        {
            return new Task(() =>
            {
                _notificationsTable.DeleteRowAsync(notification.PartitionKey, notification.RowKey);
                notification.PartitionKey = ToTicks(utcDateTimeToSend);
                _notificationsTable.InsertRowAsync(notification);
            });
        }));        
}

【问题讨论】:

    标签: c# task-parallel-library


    【解决方案1】:

    您需要启动这些任务。此外,您可以使您的 Lamba 异步,并在正文中使用 await。 (假设 DeleteRowAsync/InsertRowAsync 返回 Task)

    如果您不需要重新捕获 SynchronizationContext,我建议使用 ConfigureAwait(false)。

    IList<TNotificationEntity> notifications =
        await _notificationsTable.GetRowsByPartitionKeyAndRowKeyAsync(ToTicks(_now), userId, QueryComparisons.GreaterThanOrEqual)
        .ConfigureAwait(false);
    await Task.WhenAll(
        notifications.Select(notification =>
        {
            return Task.Run(async () =>
            {
                await _notificationsTable.DeleteRowAsync(notification.PartitionKey, notification.RowKey).ConfigureAwait(false);
                notification.PartitionKey = ToTicks(utcDateTimeToSend);
                await _notificationsTable.InsertRowAsync(notification).ConfigureAwait(false);
            });
        })).ConfigureAwait(false);
    

    也就是说,如果您的意图是在单独的 ThreadPool 线程中运行许多这些通知。这意味着您可能有多个并行删除/插入。这是你的意图吗? GetRowsByPartitionKeyAndRowKeyAsync 会不会返回大量数据?

    是否可以创建一个更基于批处理的方法,您可以在其中传递通知并在与数据库的单个连接中执行?

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 2020-09-19
      • 1970-01-01
      相关资源
      最近更新 更多