天天看點

多線程與異步委托示例之一

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
           

繼續閱讀