2013-06-12 42 views
0

我有WPF應用程序在按鈕點擊處理程序我想要啓動多個任務(其中每個可能執行長時間運行的操作)。從按鈕單擊(UI線程)運行多個任務 - 如何知道它們是成功還是失敗?

我想向用戶報告是否所​​有任務都成功,或者如果沒有,那麼單個任務的錯誤是什麼。

雖然區分至少一個異常或所有成功,我看不到一個很好的方法。

using System; 
using System.Diagnostics; 
using System.Threading.Tasks; 
using System.Windows; 

namespace WPFTaskApp 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 

      Task t1 = new Task(DoSomething); 
      Task t2 = new Task(DoSomethingElse); 

      t1.Start(); 
      t2.Start(); 

      // So now both tasks are running. 
      // I want to display one of two messages to the user: 
      // If both tasks completed ok, as in without exceptions, then notify the user of the success 
      // If an exception occured in either task notify the user of the exception. 

      // The closest I have got to the above is to use ContinueWhenAll, but this doesn't let 
      // me filter on the completion type 

      Task[] tasks = { t1, t2 }; 

      Task.Factory.ContinueWhenAll(tasks, f => 
       { 
        // This is called when both tasks are complete, but is called 
        // regardless of whether exceptions occured. 
        MessageBox.Show("All tasks completed"); 
       }); 
     } 

     private void DoSomething() 
     { 
      System.Threading.Thread.Sleep(1000); 
      Debug.WriteLine("DoSomething complete."); 
     } 

     private void DoSomethingElse() 
     { 
      System.Threading.Thread.Sleep(4000); 
      throw new Exception(); 
     } 
    } 
} 

非常感謝您的任何幫助。

回答

5

在你的延續,你可以查看每個任務的例外:

Task.Factory.ContinueWhenAll(tasks, f => 
      { 
       if (t1.Exception != null) 
       { 
        // t1 had an exception 
       } 
       if (t2.Exception != null) 
       { 
        // t2 had an exception 
       } 

       // This is called when both tasks are complete, but is called 
       // regardless of whether exceptions occured. 
       MessageBox.Show("All tasks completed"); 
      }); 
+0

注意'F'是Task's的'數組,也。所以你可以使用它而不是關閉「任務」。 –

+0

@MattSmith是的,但是更難以知道,哪一個是哪個。關閉它們使得這一點顯而易見,這就是我爲什麼這樣寫的原因。 –

+0

同意 - 只是指出來。 –

相關問題