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
.
Asked
Active
Viewed 3,505 times
3

Uriel Katz
- 319
- 1
- 8
- 21
-
I agree with you that since you are not guaranteed to execute on the same thread that the safest way to "share" the data is to put it in a public variable and then use some thread-safe access mechanism to ensure there is no deadlock. – Karl Anderson Jul 30 '13 at 00:35
1 Answers
3
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 :

J...
- 30,968
- 6
- 66
- 143