I used the IsBusy property in the WaitForBackgroundThreadToComplete() method, but IsBusy always returns true even when the BGW has finished
void
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// some long task here....
// some long task continued....
// console message to indicate task completion
Console.WriteLine("Background doWork completes");
}
private
void WaitForBackgroundThreadToComplete()
{
int i = 0;
while (backgroundWorker1.IsBusy)
{
Console.WriteLine(i++);
System.Threading.
Thread.Sleep(1000);
}
}
Assume that the thread is still running (DoWork is in progress) and I call WaitForBackgroundThreadToComplete,
In my output, I see the message "Background doWork completes" indicating my backgroundWorker is done, but the IsBusy continues to be true and WaitForBackgroundThreadToComplete goes in an infinite loop.
Instead of this, if I set a boolean variable in the DoWork event it works satisfactorily, please refer to the code below
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// some long task here....
// some long task continued....
// set boolean variable to indicate work is completed
workCompleted = true;
}
private void WaitForBackgroundThreadToComplete()
{
int i = 0;
while (workCompleted == false)
{
Console.WriteLine(i++);
System.Threading.Thread.Sleep(1000);
}
}
However, my problem is I have to update the UI after DoWork event. To do that, I use the BackGroundWorker's RunWorkCompleted event. This event fires when DoWork is completed
void
backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
workCompleted = true;
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// some long task here....
// some long task continued....
}
private void WaitForBackgroundThreadToComplete()
{
int i = 0;
while (workCompleted == false)
{
Console.WriteLine(i++);
System.Threading.Thread.Sleep(1000);
}
}
if I do this, then WaitForBackGroundThreadToComplete method goes in an infinite loop. This is because I think, RunWorkerCompleted method runs on the main thread (and not the worker thread) and I am getting the thread to sleep in the WaitForBackgroundThreadToComplete method.
in short i need to do the following things
1. run a process in the background
2. once the background process completes, i want to update the ui
3. until that time, the user is free to use the UI, but at one particular point I need to wait for the background thread to finish only then i can allow the user to proceed.