由于这些过程不能为函数也不能使用 ByRef 参数,因而从运行于不同线程的过程返回值是很复杂的。 返回值的最简单方法是:使用 BackgroundWorker 组件来管理线程,在任务完成时引发事件,然后用事件处理程序处理结果。
下面的示例通过从运行于单独线程的某过程引发一个事件来返回值:
Private Class AreaClass2
Public Base As Double
Public Height As Double
Function CalcArea() As Double
' Calculate the area of a triangle.
Return 0.5 * Base * Height
End Function
End Class
Private WithEvents BackgroundWorker1 As New System.ComponentModel.BackgroundWorker
Private Sub TestArea2()
Dim AreaObject2 As New AreaClass2
AreaObject2.Base = 30
AreaObject2.Height = 40
' Start the asynchronous operation.
BackgroundWorker1.RunWorkerAsync(AreaObject2)
End Sub
' This method runs on the background thread when it starts.
Private Sub BackgroundWorker1_DoWork(
ByVal sender As Object,
ByVal e As System.ComponentModel.DoWorkEventArgs
) Handles BackgroundWorker1.DoWork
Dim AreaObject2 As AreaClass2 = CType(e.Argument, AreaClass2)
' Return the value through the Result property.
e.Result = AreaObject2.CalcArea()
End Sub
' This method runs on the main thread when the background thread finishes.
Private Sub BackgroundWorker1_RunWorkerCompleted(
ByVal sender As Object,
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs
) Handles BackgroundWorker1.RunWorkerCompleted
' Access the result through the Result property.
Dim Area As Double = CDbl(e.Result)
MessageBox.Show("The area is: " & Area.ToString)
End Sub
classAreaClass2 { publicdoubleBase; publicdoubleHeight; publicdoubleCalcArea() { //Calculatetheareaofatriangle. return0.5*Base*Height; } } privateSystem.ComponentModel.BackgroundWorkerBackgroundWorker1 =newSystem.ComponentModel.BackgroundWorker(); privatevoidTestArea2() { InitializeBackgroundWorker(); AreaClass2AreaObject2=newAreaClass2(); AreaObject2.Base=30; AreaObject2.Height=40; //Starttheasynchronousoperation. BackgroundWorker1.RunWorkerAsync(AreaObject2); } privatevoidInitializeBackgroundWorker() { //AttacheventhandlerstotheBackgroundWorkerobject. BackgroundWorker1.DoWork+= newSystem.ComponentModel.DoWorkEventHandler(BackgroundWorker1_DoWork); BackgroundWorker1.RunWorkerCompleted+= newSystem.ComponentModel.RunWorkerCompletedEventHandler(BackgroundWorker1_RunWorkerCompleted); } privatevoidBackgroundWorker1_DoWork( objectsender, System.ComponentModel.DoWorkEventArgse) { AreaClass2AreaObject2=(AreaClass2)e.Argument; //ReturnthevaluethroughtheResultproperty. e.Result=AreaObject2.CalcArea(); } privatevoidBackgroundWorker1_RunWorkerCompleted( objectsender, System.ComponentModel.RunWorkerCompletedEventArgse) { //AccesstheresultthroughtheResultproperty. doubleArea=(double)e.Result; MessageBox.Show("Theareais:"+Area.ToString()); }
可以通过使用 QueueUserWorkItem 方法的可选 ByVal 状态对象变量为线程池线程提供参数和返回值。 线程计时器线程也支持将状态对象用于此目的。 有关线程池和线程计时器的信息,请参见 线程池(C# 和 Visual Basic) 和 线程计时器(C# 和 Visual Basic)。
本文介绍了一种在多线程环境下返回值的方法,利用BackgroundWorker组件管理线程并触发事件,通过事件处理程序获取结果。同时介绍了如何使用QueueUserWorkItem方法为线程池线程提供参数和返回值。
2269

被折叠的 条评论
为什么被折叠?



