Friend Class StateObj
Friend StrArg As String
Friend IntArg As Integer
Friend RetVal As String
End Class
Sub ThreadPoolTest()
Dim TPool As System.Threading.ThreadPool
Dim StObj1 As New StateObj()
Dim StObj2 As New StateObj()
' 设置一些字段,用作状态对象中的参数。
StObj1.IntArg = 10
StObj1.StrArg = "某个字符串"
StObj2.IntArg = 100
StObj2.StrArg = "另一个字符串"
' 将一个任务排队
TPool.QueueUserWorkItem(New System.Threading.WaitCallback _
(AddressOf SomeOtherTask), StObj1)
' 将另一个任务排队
TPool.QueueUserWorkItem(New System.Threading.WaitCallback _
(AddressOf AnotherTask), StObj2)
End Sub
Sub SomeOtherTask(ByVal StateObj As Object)
' 将状态对象字段用作参数。
Dim StObj As StateObj
StObj = CType(StateObj, StateObj) ' 强制转换为正确的类型。
MsgBox("StrArg 包含字符串" & StObj.StrArg)
MsgBox("IntArg 包含数字" & CStr(StObj.IntArg))
' 将字段用作返回值。
StObj.RetVal = "SomeOtherTask 的返回值"
End Sub
Sub AnotherTask(ByVal StateObj As Object)
' 将状态对象字段用作参数。
' 状态对象作为 Object 进行传递。
' 将其强制转换为特定的类型以使其更易于使用。
Dim StObj As StateObj
StObj = CType(StateObj, StateObj)
MsgBox("StrArg 包含字符串 " & StObj.StrArg)
MsgBox("IntArg 包含数字" & CStr(StObj.IntArg))
' 将字段用作返回值。
StObj.RetVal = "AnotherTask 的返回值"
End Sub