2013-03-28 65 views
0

這是代碼:如何等待兩個BackgrandWorker的RunWorkerCompleted事件完成?

private void button1_Click(object sender, EventArgs e) 
    { 
     ParaClass pcs = new ParaClass(); 
     pcs.strPath = textBox1.Text; 
     pcs.sendedGrid = ugSrc; 
     this.backgroundWorker1.RunWorkerAsync(pcs); 

     ParaClass pcsB = new ParaClass(); 
     pcsB.strPath = textBox2.Text; 
     pcsB.sendedGrid = ultraGrid2; 

     this.backgroundWorker2.RunWorkerAsync(pcsB); 

     doSomething(); 
    } 

,並在這兩個backgrandworker1 & backgrandworker2「完滿成功事件,我這樣寫代碼:

private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) 
    { 
      doSomethingelsebk1(); 
    } 

    private void backgroundWorker2_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) 
    { 
      doSomethingelsebk2(); 
    } 

現在的問題是:在Button1的的點擊事件的函數DoSomething的()必須等待雙方完成事件的完成。 如果我改變DoSomething的()來

private void backgroundWorker2_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) 
    { 
      doSomethingelsebk2(); 
      doSomething(); 
    } 

然後,因爲有兩個線程,我不知道哪個線程將首先完成,所以如何解決

+0

爲什麼不乾脆讓backgroundworker2正常的方法,而不是異步。 – CathalMF 2013-03-28 09:24:55

+0

或者你可以使用AsyncCallBack委託http://msdn.microsoft.com/en-GB/library/system.asynccallback(v=vs.90).aspx 這裏是使用異步回調http://的一個很好的例子stackoverflow.com/questions/1047662/what-is-asynccallback – CathalMF 2013-03-28 09:26:38

回答

0

創建2個標誌代表完整的狀態2的BackgroundWorker

打開RunWorkerCompleted事件中的各個標誌,然後調用doSomething()方法。

doSomething方法中,檢查兩個標誌是否都打開,然後繼續執行,否則返回。

0

創建2個AutoResetEvents,在每個Background工作完成時設置它們,並在主方法中用WaitHandle等待它們全部。

WaitHandle[] handles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false)}; 

private void button1_Click(object sender, EventArgs e) 
{ 
    ParaClass pcs = new ParaClass(); 
    pcs.strPath = textBox1.Text; 
    pcs.sendedGrid = ugSrc; 
    this.backgroundWorker1.RunWorkerAsync(pcs); 

    ParaClass pcsB = new ParaClass(); 
    pcsB.strPath = textBox2.Text; 
    pcsB.sendedGrid = ultraGrid2; 

    this.backgroundWorker2.RunWorkerAsync(pcsB); 

    WaitHandle.WaitAll(this.handles); 
    doSomething(); 
} 


private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) 
{ 
     doSomethingelsebk1(); 
     ((AutoResetEvent)this.handles[0]).Set(); 
} 

private void backgroundWorker2_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) 
{ 
     doSomethingelsebk2(); 
     ((AutoResetEvent)this.handles[1]).Set(); 
} 
+0

感謝您的回覆,我按照您的說法提供了mofidy代碼,但收到錯誤消息:不支持WAA線程上的多個句柄的WaitAll。 – user2147152 2013-03-28 15:26:12

+0

嗨,你可以看看:http://stackoverflow.com/questions/4192834/waitall-for-multiple-handles-on-a-sta-thread-is-not-supported – JoanComasFdz 2013-04-02 09:04:08