Imports System
Imports System.Threading
Partial Public Class Form1
Inherits Form
'创建一个Button对象
Private button As New Button()
'构造函数
Sub New()
' This call is required by the designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call.
'设置按钮的属性
button.Size = New Size(150, 100)
'大小
AddHandler button.Click, AddressOf Button1_Clicked
'注册事件
button.Text = "点击开始测试"
'设置显示文本
Me.Controls.Add(button)
'添加到窗体上
'设置窗体的标题栏文本
Me.Text = "多线程范例"
End Sub
'按钮的Click事件响应方法
Public Sub Button1_Clicked(ByVal sender As Object, ByVal e As EventArgs)
'启动一个线程
Dim a As New Thread(AddressOf ThreadProc)
a.Start()
End Sub
'线程函数
Public Sub ThreadProc()
'this.Invoke就是跨线程访问ui的方法,也是本文的范例
'首先invoke一个匿名委托,将button对象禁用
Dim a As BtnEnable = New BtnEnable(AddressOf BtnFalse)
Me.Invoke(a) '不带参数委托
'记录一个时间戳,以演示倒计时效果
Dim b As InputValue = New InputValue(AddressOf ReadValue)
Dim tick As Integer = Environment.TickCount
While Environment.TickCount - tick < 1000
' 跨线程调用更新窗体上控件的属性,这里是更新这个按钮对象的Text属性
Me.Invoke(b, tick) '带参数委托
'做一个延迟,避免太快了,视觉效果不好。
Thread.Sleep(200)
End While
' '演示,10次数字递增显示
Dim b1 As InputValue = New InputValue(AddressOf ReadInt)
For i As Integer = 0 To 9
Me.Invoke(b1, i)
Thread.Sleep(200)
Next
'虽然不是循环内,请不要忘记,你的调用依然在辅助线程中,所以,还是需要invoke的。
'还原状态,设置按钮的文本为初始状态,设置按钮可用。
Dim c As BtnEnable = New BtnEnable(AddressOf BtnReset)
Me.Invoke(c)
End Sub
Public Delegate Sub BtnEnable()
Public Sub BtnReset()
button.Text = "点击开始测试01"
button.Enabled = True
End Sub
Public Sub BtnFalse()
button.Text = 0
button.Enabled = False
End Sub
Public Delegate Sub InputValue(ByVal pValue As Integer)
Public Sub ReadValue(ByVal pValue As Integer)
button.Text = (1000 - Environment.TickCount + pValue).ToString() & "微秒后开始更新"
End Sub
Public Sub ReadInt(ByVal pValue As Integer)
button.Text = pValue.ToString
End Sub
End Class