如何等待两个BackgrandWorker的RunWorkerCompleted事件完成?

时间:2013-03-28 09:22:13

标签: c#

这就是代码:

   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'complet事件,我写这样的代码:

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

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

现在的问题是:button1的click事件中的函数doSomething()必须等待backgrandworker的完成事件完成。 如果我将doSomething()更改为

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

然后,因为有两个线程,我不知道哪个线程会先完成,所以解决方案是什么

2 个答案:

答案 0 :(得分:0)

创建2个标志,表示2 BackgroundWorker的完整状态。

RunWorkerCompleted事件中启用每个标记,然后调用doSomething()方法。

doSomething方法中,检查两个标志是否都已打开,然后继续执行,否则返回。

答案 1 :(得分:0)

创建2个AutoResetEvents,在每个后台工作程序完成时设置它们,并在主方法中使用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();
}