BackgroundWorker Returns a value?

The following code adds numbers from 1 to 100 and returns the sum. What I'm trying to do is run the calculations in the workworker and return the value. The problem is that returnValue returns before DoWork completes. How can I wait for my background to finish before returning a value? (It seems I can't return the return to my DoWork ...)

double returnValue = 0;

var b = new BackgroundWorker();
b.DoWork += new DoWorkEventHandler(
    delegate(object sender, DoWorkEventArgs e) {
        for(int i=0;i<100;i++){
            returnValue += (i+1);
        }
    }
);

b.RunWorkerAsync();
return returnValue;

Addendum: Would it be better to send a message pump in the same thread instead of running it on the background desktop?

Also, this is just a sample code, my actual code takes more than a minute.

+3
source share
4 answers

RunWorkerCompleted . .

, DoWorkEventHandler, :

b.DoWork += new DoWorkEventHandler(
    delegate(object sender, DoWorkEventArgs e) {
        double returnValue = 0;
        for(int i=0;i<100;i++){
            returnValue += (i+1);
        }
        return returnValue;
    }
);
+3

, , , , - RunWorkerCompleted. , DoWork . , , , .

0

postet : , : -)

, , .

This may be the effect of starting async. you can tell in the background when to start or just start. if you don’t say that he should start NOW, he will start when C # thinks that the best time to start is :-)

0
source

You are trying to perform a synchronous operation with BackgroundWorker, which it is BAD . But if you need to, you can use the IsBusy flag.

double returnValue = 0;

var b = new BackgroundWorker();
b.DoWork += new DoWorkEventHandler(
    delegate(object sender, DoWorkEventArgs e) {
        for(int i=0;i<100;i++){
            returnValue += (i+1);
        }
    }
);

b.RunWorkerAsync();
while(b.IsBusy){
  Application.DoEvents();
}
return returnValue;
-1
source

All Articles