2011-08-26 63 views
1

以此段。是什麼阻止Task.Factory.ContinueWhenAll調用指定的Action?

IEnumerable<Task> tasks = CreateTierCleanupTasks(); 
if (tasks.Count() > 0) { 
    Task.Factory.ContinueWhenAll(tasks.ToArray(), OnTierCleanupCompleted, 
     m_CancellationTokenSource.Token, 
     TaskContinuationOptions.None, 
     m_TaskScheduler); 
    Array.ForEach(tasks.ToArray(), (t) => t.Start()); 
    OnTierCleanupStarted(); 
} 

這裏是指定的操作。

private void OnTierCleanupCompleted(Task[] tasks) { 
    if (tasks.All(task => task.IsCompleted) && TierCleanupCompleted != null) { 
     TierCleanupCompleted(this, new EventArgs()); 
    } 
    RunTierData(); 
} 

現在在測試運行中,通常會創建5個任務,並且它們都運行正常。我在函數體的末尾放了一個Debug.WriteLine("Task Return");來驗證每個任務是否相應返回。爲ContinueWhenAll指定的操作是從未發起過。我無法弄清楚爲什麼。我認爲ContinueWhenAll的行爲會在所有指定的操作返回時(即完成)觸發Action。

什麼會阻止ContinueWhenAll發射Action?

編輯,這裏是創建任務的方法:

private IEnumerable<Task> CreateTierCleanupTasks() { 
    using (FaultTrackObjectContext context = new FaultTrackObjectContext(this.TierInformation.EntityConnectionString)) { 
     foreach (TeamCollection collection in context.TeamCollections.ToArray()) { 
      yield return new Task(DeleteTeamCollection, collection.ID, m_CancellationTokenSource.Token); 
     } 
    } 
} 
+0

注意,在你的代碼,'OnTierCleanupCompleted()'可以稱爲** **前'OnTierCleanupStarted()'(如果它的工作)。 – svick

回答

1

的問題是,你迭代的CreateTierCleanupTasks()幾次的結果。每一次,它創建一套新的Task s。所以你在等待一些任務,但開始不同的任務。

您的代碼應該是這樣的:

Task[] tasks = CreateTierCleanupTasks().ToArray(); 
if (tasks.Length > 0) { 
    Task.Factory.ContinueWhenAll(tasks, OnTierCleanupCompleted, 
     m_CancellationTokenSource.Token, 
     TaskContinuationOptions.None, 
     m_TaskScheduler); 
    OnTierCleanupStarted(); 
    Array.ForEach(tasks, (t) => t.Start()); 
}