6

我想同步调用后台工作人员。我希望在后台工作人员完成执行后结束代码的执行。我的 BackgroundWorker 代码在这里:

{
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += DoWork;
    worker.RunWorkerCompleted += RunWorkerCompleted;
    ...
    worker.RunWorkerAsync();
    //wait for execution to end 
}

一种方法是再次检查状态 n 直到其执行完成,但是还有其他好的方法吗?

4

3 回答 3

18

如果你不希望你的代码异步执行,不要把它放在BackgroundWorker...

{ 
    DoWork();
} 

但是,如果有一些不明确的原因绝对需要在 中包含代码,则BackgroundWorker可以使用以下内容:

ManualResetEvent mre = new ManualResetEvent(false);
BackgroundWorker worker = new BackgroundWorker(); 
worker.DoWork += DoWork; 
worker.RunWorkerCompleted += (s, e) => 
                             {
                                 RunWorkerCompleted(s, e); 
                                 mre.Set();
                             };
// ... 
worker.RunWorkerAsync();
mre.WaitOne();
于 2012-08-31T10:38:59.713 回答
2

目标: BackgroundWorker 应该同步执行。

创建了一个windows应用程序表单。单击 button1 时,它应该同步执行 BackgroundWorker 并返回参与 UI,因此用户在完成 BackgroundWorker 任务之前无法执行任何操作。

public partial class Form1 : Form 
{ 

    public Form1() 
    { 
        InitializeComponent(); 
    }

    BGimplent obj = null;

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;
         obj = new BGimplent();
        obj.eveBG += obj_eveBG;
        i = 5;
        obj.MyProperty = 5;
        obj.DoConfig();
        obj.ManualReset.WaitOne();

        obj.MyProperty = 10;
        obj.MyProperty = 11;
        obj.MyProperty = 12;
        obj.MyProperty = 13;

        obj.MyProperty = 14;
    }

    void obj_eveBG(string s)
    {
        obj.ManualReset.Set();
        MessageBox.Show(s);
    }
}



/*
*******************************************************
    Paste below code in adding new class i.e. Class1


*/
public delegate void delBG(string s);

class BGimplent
{
    public event  delBG eveBG;


    private ManualResetEvent mnuReset = new ManualResetEvent(false);
    public ManualResetEvent ManualReset { get; set; }

    public int MyProperty { get; set; }

    BackgroundWorker bgWorker = new BackgroundWorker();
    public void DoConfig()
    {
        ManualReset = mnuReset;

        bgWorker.DoWork += bgWorker_DoWork;
        bgWorker.ProgressChanged += bgWorker_ProgressChanged;
        bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
        bgWorker.RunWorkerAsync();            
    }

    void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {   
        Thread.Sleep(5000);
        if (eveBG != null)
            eveBG("Value of MyProperty: " + MyProperty.ToString());
    }

}
于 2017-08-31T12:40:27.430 回答
0

您的代码//wait for execution to end应该放在worker_RunWorkerCompleted方法中。

于 2015-01-21T13:25:34.517 回答