Waiting for the completion of any of these BackgroundWorker

There is a sequence for FORM (some user interface) that must be loaded using the service. This download is currently in the BackgroundWorker Thread. Now, since performance is slow ... We decided to split FORMS by 2 and start loading in parallel using another BackgroundWorker on top of the existing thread.

Now, a script is any of BackgroundWorker that needs to wait for another to complete. So how to implement it.

I tried using AutoResetEvent. but I could not achieve this.

Any help is appreciated.

+3
source share
5

, , BackgroundWorker . , , - ( ) . , ; .

public class Form1 : Form
{
    private object download1Result;
    private object download2Result;

    private void BeginDownload()
    {
        // Next two lines are only necessary if this is called multiple times
        download1Result = null;
        download2Result = null;

        bwDownload1.RunWorkerAsync();
        bwDownload2.RunWorkerAsync();
    }

    private void bwDownload1_RunWorkerCompleted(object sender,
        RunWorkerCompletedEventArgs e)
    {
        download1Result = e.Result;
        if (download2Result != null)
            DisplayResults();
    }

    private void bwDownload2_RunWorkerCompleted(object sender,
        RunWorkerCompletedEventArgs e)
    {
        download2Result = e.Result;
        if (download1Result != null)
            DisplayResults();
    }

    private void DisplayResults()
    {
        // Do something with download1Result and download2Result
    }
}

, object , object, , .

, ; RunWorkerCompleted , . lock, AutoResetEvent .. - , null.

+2

AutoResetEvent WaitAll, . AutoResetEvent OnRunWorkerCompleted.

+1

- , , , Power Threading Library, , n ( ), .

, , , . ( Silverlight Compact Framework), , .

,

+1
int completedCount = 0;

void threadProc1() { //your thread1 proc
//do something
....

completedCount++;
while (completedCount < 2) Thread.Sleep(10);
//now both threads are done
}

void threadProc2() { //your thread1 proc
//do something
....

completedCount++;
while (completedCount < 2) Thread.Sleep(10);
//now both threads are done
}
0

2 BackgroundWorker, , . , , , , . ..

By the way, it’s just so clear that you should NEVER call a lock function, such as WaitAll, from a user interface thread. This will force the user interface to completely block, which will make you wonder what is happening WTF :)

0
source

Source: https://habr.com/ru/post/1730951/


All Articles