vb.net中线程委托的简单实例

前端之家收集整理的这篇文章主要介绍了vb.net中线程委托的简单实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

[原帖地址]http://topic.csdn.net/u/20111019/17/ac098c48-ed25-4e1f-acd0-ec192ca44eac.html

'原先错误的写法!
-------------------------
Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click
    Dim MyThread As New System.Threading.Thread(AddressOf sum)
    MyThread.Start()
End Sub
Private Sub sum()
    Dim i,sum As Integer
    For i = 0 To 100
        sum += i
    Next
    Me.Text = CStr(sum)  '在这里就会报错,教我"如何跨线程调用windows窗体控件",表示没看懂
End Sub
-------------------------------------
'正确的线程委托写法
-------------------------------------
Private Delegate Sub myDelegate(ByVal myString As String) '自定义一个委托

Private Sub SetWindowText(ByVal myString As String) '与委托相同签名的函数或过程
Me.Text = myString
End Sub

Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles Button1.Click
Dim MyThread As New System.Threading.Thread(AddressOf sum)
MyThread.Start()
End Sub

Private Sub sum()
Dim i,sum As Integer
For i = 0 To 100
sum += i
Next
Me.Invoke(New myDelegate(AddressOf SetWindowText),sum.ToString) '委托的调用
End Sub

猜你在找的VB相关文章