我想同步调用后台工作程序。我希望执行代码在backgroundworker完成执行时结束。 我的BackgroundWorker代码在这里:
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += RunWorkerCompleted;
...
worker.RunWorkerAsync();
//wait for execution to end
}
这样做的一种方法是再次检查状态,直到执行完成,但还有其他好办法吗?
答案 0 :(得分:15)
如果您不希望代码异步执行,请不要将其放在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();
答案 1 :(得分: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());
}
}
答案 2 :(得分:0)
//wait for execution to end
之后的代码应放在worker_RunWorkerCompleted
方法中。