Observe the following piece of code:
var handler = GetTheRightHandler();
var bw = new BackgroundWorker();
bw.RunWorkerCompleted += OnAsyncOperationCompleted;
bw.DoWork += OnDoWorkLoadChildren;
bw.RunWorkerAsync(handler);
Now suppose I want to wait until bw
finishes working. What is the right way to do so?
My solution is this:
bool finished = false;
var handler = GetTheRightHandler();
var bw = new BackgroundWorker();
bw.RunWorkerCompleted += (sender, args) =>
{
OnAsyncOperationCompleted(sender, args);
finished = true;
});
bw.DoWork += OnDoWorkLoadChildren;
bw.RunWorkerAsync(handler);
int timeout = N;
while (!finished && timeout > 0)
{
Thread.Sleep(1000);
--timeout;
}
if (!finished)
{
throw new TimedoutException("bla bla bla");
}
But I do not like it.
I have considered replacing the finished
flag with a synchronization event, set it in the RunWorkerCompleted
handler and block on it later instead of doing the while-sleep loop.
Alas, it is wrong, because the code may run in the WPF or WindowsForm synchronization context, in which case I would block the same thread as the RunWorkerCompleted
handler runs on, which is clearly not very smart move.
I would like to know of a better solution.
Thanks.
EDIT:
P.S.
- The sample code is so contrived intentionally to clarify my question. I am perfectly aware of the completion callback and yet I want to know how to wait till completion. That is my question.
- I am aware of
Thread.Join
, Delegate.BeginInvoke
, ThreadPool.QueueUserWorkItem
, etc... The question is specifically about BackgroundWorker
.
EDIT 2:
OK, I guess it will be much easier if I explain the scenario.
I have a unit test method, which invokes some asynchronous code, which in turn ultimately engages a BackgroundWorker
to which I am able to pass a completion handler. All the code is mine, so I can change the implementation if I wish to.
I am not going, however, to replace the BackgroundWorker
, because it automatically uses the right synchronization context, so that when the code is invoked on a UI thread the completion callback is invoked on the same UI thread, which is very good.
Anyway, it is possible that the unit test method hits the end before the BW finishes its work, which is not good. So I wish to wait until the BW completes and would like to know the best way for it.
There are more pieces to it, but the overall picture is more or less like I have just described.
question from:
https://stackoverflow.com/questions/1333058/how-to-wait-correctly-until-backgroundworker-completes 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…