2013-02-13 73 views
0

我想在下面完成每個任務時更新進度條。檢測每個任務何時完成

的方法VAR continuation2 = Task.Factory.ContinueWhenAny(.....不工作。

什麼是做這種正確的方法是什麼?

C#代碼

private void radButtonInsertManyErrors_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       radProgressBarStatus.Maximum = int.Parse(radTextBoxNumberofErrorsInsert.Text); 
       radProgressBarStatus.Value1 = 0; 


       Task<int>[] tasks = new Task<int>[int.Parse(radTextBoxNumberofErrorsInsert.Text)]; 

       for (int i = 0; i < int.Parse(radTextBoxNumberofErrorsInsert.Text); i++) 
       { 
        int x = i; 
        tasks[i] = new Task<int>(() => 
        { 

         //insert the error into table FA_Errors 
         Accessor.Insert_FAErrors(BLLErrorCodes.BLL_Error_Codes.Error_Log_Event_Login.ToString(), 
                (int)BLLErrorCodes.BLL_Error_Codes.Error_Log_Event_Login, 
                "Some Error", "", 
               MethodBase.GetCurrentMethod().DeclaringType.Namespace.ToString(), 
               MethodBase.GetCurrentMethod().Name.ToString(), 
               BLLErrorCategory.BLL_Error_Category.WEB_APP.ToString(), 
               "pc source", "damo", 
               sConn.ToString()); 
         return 1; 


        }); 
       } 

       var continuation = Task.Factory.ContinueWhenAll(
          tasks, 
          (antecedents) => 
          { 
           RadMessageBox.Show("Finished inserting errors "); 
          }); 


       var continuation2 = Task.Factory.ContinueWhenAny(
       tasks, 
       (antecedents) => 
       { 
         radProgressBarStatus.Value1++; 

       }); 


       for (int i = 0; i < int.Parse(radTextBoxNumberofErrorsInsert.Text); i++) 
        tasks[i].Start(); 
       // Use next line if you want to block the main thread until all the tasks are complete 
       //continuation.Wait(); 


      } 
      catch (Exception ex) 
      { 

       MessageBox.Show(ex.Message.ToString()); 

      } 

     } 

回答

4

您可以使用此功能:

public static void TaskProgress(IEnumerable<Task> tasks, Action<int> callback) 
{ 
    int count = 0; 
    foreach (var task in tasks) 
     task.ContinueWith(t => callback(Interlocked.Increment(ref count))); 
} 

將每一項任務的完成當前任務數完成時調用回調。請注意,回調不是同步的,因此可以在前一個回調仍在運行時調用回調。

+0

我該如何調用該方法? – user1438082 2013-02-13 21:10:18

+1

@ user1438082'TaskProgress(tasks,count => Invoke(new MethodInvoker(()=> radProgressBarStatus.Value1 = count)));' – Servy 2013-02-13 21:13:57

+0

我得到錯誤「System.Windows.Forms.Control的最佳重載方法匹配.Invoke(System.Delegate,params object [])'有一些無效參數「插入這行代碼後 – user1438082 2013-02-13 21:25:31

2

設置每個任務的延續時間,在完成每項任務時保持一個(線程安全)計數器的完成和更新UI。

其實,Task.WhenAll的確保持這樣一個櫃檯。它只是無法訪問。

+0

因此,如果我有1000個任務 - 那麼我必須創建1000個連續? – user1438082 2013-02-13 21:03:48

+2

@ user1438082是的。這需要完成。有一些功能爲你做它只會隱藏它,不會阻止它發生。 – Servy 2013-02-13 21:06:50

+0

延期費用相對便宜。肯定比任務要便宜得多,因此任務機構的成本掩蓋了延續的成本。 – usr 2013-02-13 21:20:27