Pass values from BackgroundWorker DoWork to BackgroundWorker Completed

3.6k views Asked by At

How do I pass a value from BackgroundWorker DoWork to BackgroundWorker Completed? Since BackgroundWorker Completed is not called by BackgroundWorker DoWork I am not sure how to do this except declare a public variable. Essentially, I want BackgroundWorker Completed to accept through ByVal a variable from BackgroundWorker DoWork.

1

There are 1 answers

0
J... On BEST ANSWER

When you declare your DoWork function, note that it has some handy arguments built in :

Private Sub backgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) _
                                                  Handles backgroundWorker1.DoWork

and also note similar arguments for the RunWorkerCompleted handler :

Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
                                          ByVal e As RunWorkerCompletedEventArgs) _
                                       Handles backgroundWorker1.RunWorkerCompleted

Critically, you have access to e.Result, which can be any object, in the RunWorkerCompletedEventArgs, and also e.Result in your DoWorkEventArgs - the latter is passed to the former when the method completes so at the end of your worker method just set :

e.Result = myResult

and then in your RunWorkerCompleted handler you can access it also via :

if e.Result = (whatever) then 
    .... etc

Reference :

RunWorkerCompletedEventArgs.Result Property : MSDN

DoWorkEventArgs.Result Property : MSDN