同步调用BackgroundWorker [英] Calling BackgroundWorker synchronously
问题描述
我想同步给后台工作人员打电话.我希望代码在背景工作人员完成执行后结束执行. 我的BackgroundWorker代码在这里:
I want to call the background worker synchronously. I want execution of the code to end when backgroundworker has completed its execution. My code for BackgroundWorker is here :
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.RunWorkerCompleted += RunWorkerCompleted;
...
worker.RunWorkerAsync();
//wait for execution to end
}
一种方法是再次在执行完成之前再次检查状态,但是还有其他好的方法吗?
One way of doing it will be to check the status again n again until its execution is completed but is there any other good way of doing it ?
推荐答案
如果您不希望代码异步执行,请不要将其放入BackgroundWorker
...
If you don't want your code to execute asynchronously, don't put it in a BackgroundWorker
...
{
DoWork();
}
但是,如果出于某些原因导致您绝对需要在BackgroundWorker
中包含代码,则可以使用以下代码:
However, if there is some obscure reason why you absolutely need to have the code in the BackgroundWorker
, you can use the following:
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();
这篇关于同步调用BackgroundWorker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!