Pass values from BackgroundWorker DoWork to BackgroundWorker Completed

情到浓时终转凉″ 提交于 2019-12-11 00:04:38

问题


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:


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



来源:https://stackoverflow.com/questions/17936438/pass-values-from-backgroundworker-dowork-to-backgroundworker-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!