将值从BackgroundWorker DoWork传递到BackgroundWorker已完成 [英] Pass values from BackgroundWorker DoWork to BackgroundWorker Completed
问题描述
如何将值从BackgroundWorker
DoWork
传递给BackgroundWorker
Completed
?由于BackgroundWorker
DoWork
不会调用BackgroundWorker
Completed
,因此我不确定如何声明public variable
以外的方法.本质上,我希望BackgroundWorker
Completed
通过ByVal
接受BackgroundWorker
DoWork
中的变量.
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
.
推荐答案
在声明DoWork
函数时,请注意,该函数内置了一些方便的参数:
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
并注意RunWorkerCompleted
处理程序的类似参数:
and also note similar arguments for the RunWorkerCompleted
handler :
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As RunWorkerCompletedEventArgs) _
Handles backgroundWorker1.RunWorkerCompleted
重要的是,您可以访问e.Result
中的e.Result
,该对象可以是任何对象,还可以访问DoWorkEventArgs
中的e.Result
-当方法完成时,后者将传递给前者,因此您的worker方法的末尾只需设置:
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
,然后在您的RunWorkerCompleted
处理程序中,您也可以通过以下方式访问它:
and then in your RunWorkerCompleted
handler you can access it also via :
if e.Result = (whatever) then
.... etc
参考:
RunWorkerCompletedEventArgs.结果属性:MSDN
这篇关于将值从BackgroundWorker DoWork传递到BackgroundWorker已完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!