2016-04-09 67 views
0

我想調用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); 
      }); 
     }));   
} 

回答

0

您需要啓動這些任務。此外,你可以讓你的lamba異步,並在身體內使用await。 (假設DeleteRowAsync/InsertRowAsync返回任務)

如果您不需要重新捕獲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); 

也就是說,如果你的目的是運行多個在一個單獨的線程池線程的通知的。這意味着你可能有多個刪除/插入並行。這是你的意圖嗎?有可能GetRowsByPartitionKeyAndRowKeyAsync會返回大量數據嗎?

是否有可能創建一個更基於批處理的方法,其中您通過通知並將在單個連接中執行到數據庫?