多线程
- 利用委托启用不带返回值线程
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mAction As New Action(Of String)(AddressOf DoSomething)
'mAction("1")'直接调用委托,这种方式会阻塞线程
'mAction.Invoke("2")'调用委托的Invoke 方法,这种方式与直接调用委托一样,会阻塞线程
'线程执行完后,会先来这行这个函数
Dim mCallback As AsyncCallback = New AsyncCallback(Sub(ByVal ar As AsyncResult)
Dim RetS As String = ar.AsyncState '这里会得到的结果是BeginInvoke传进来的第三个参数:"hhhhh"
'Me.Text = RetS '更新不了,因为这里还是属于线程的一部分
End Sub)
'调用委托的BeginInvoke 方法,这种方式不会阻塞线程
Dim asyncResult As IAsyncResult = mAction.BeginInvoke("3", mCallback, "hhhhh")
'这里可以做一些其他事情
'
'
'asyncResult.AsyncWaitHandle.WaitOne() '阻塞线程
asyncResult.AsyncWaitHandle.WaitOne(-1) '阻塞线程,一直等待
'asyncResult.AsyncWaitHandle.WaitOne(150) '阻塞线程,最多等待150ms
End Sub
Public Sub DoSomething(ByVal mS As String)
Dim d As Double
For i As Integer = 0 To 1000000000
d += i Mod 2
Next
End Sub
- 利用委托启动带返回值的线程
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim mFun As New Func(Of String, String)(AddressOf DoSomething1)
Dim mCallback As AsyncCallback = New AsyncCallback(Sub(ByVal ar As AsyncResult)
'可以在回调中获取结果
Dim OutS1 As String = mFun.EndInvoke(ar) '这里的结果是123999
End Sub)
Dim asyncResult As IAsyncResult = mFun.BeginInvoke("123", mCallback, "hhhhh")
'也可以在外部获取结果,调用这个时会阻塞主线程,等待线程结束
Dim OutS As String = mFun.EndInvoke(asyncResult) '这里的结果是123999
End Sub
Public Function DoSomething1(ByVal mS As String) As String
Dim d As Double
For i As Integer = 0 To 1000000000
d += i Mod 2
Next
Return mS & "999"
End Function