Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for background worker to finish processing?

I have 3 background workers each processing a channel of a 24-bit Bitmap image (Y, Cb, Cr). The processing for each 8-bit image takes several seconds and they might not complete at the same time.

I want to merge the channels back into one image when I'm done. When a button is clicked, each of the backgroundWorkerN.RunWorkerAsync() is started and when they complete I set a flag for true. I tried using a while loop while (!y && !cb && !cr) { } to continually check the flags until they are true then exit loop and continue processing the code below which is the code to merge the channels back together. But instead the process never ends when I run it.

   private void button1_Click(object sender, EventArgs e)
   {
        backgroundWorker1.RunWorkerAsync();
        backgroundWorker2.RunWorkerAsync();
        backgroundWorker3.RunWorkerAsync();

        while (!y && !cb && !cr) { }

        //Merge Code
   }
like image 994
Ryder Avatar asked Dec 09 '22 05:12

Ryder


2 Answers

Building on the answer from Renuiz, I would do it this way:

private object lockObj;

private void backgroundWorkerN_RunWorkerCompleted(
    object sender, 
    RunWorkerCompletedEventArgs e)
{
    lock (lockObj)
    {
        y = true;
        if (cb && cr) // if cb and cr flags are true - 
                      // other backgroundWorkers finished work
        {
            someMethodToDoOtherStuff();
        }
    }
}
like image 57
João Lourenço Avatar answered Jan 05 '23 12:01

João Lourenço


Maybe you could set and check flags in background worker complete event handlers. For example:

private void backgroundWorkerN_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    y = true;
    if(cb && cr)//if cb and cr flags are true - other backgroundWorkers finished work
       someMethodToDoOtherStuff();
}
like image 34
Renatas M. Avatar answered Jan 05 '23 10:01

Renatas M.