Public Class Class1 Public Event ShowMsg(ByVal text As String) '宣告事件,觸發該事件即可傳出參數 Private sum As Integer '執行緒執行時傳入的參數 Property Num As Integer '設成屬性存取 Get Return sum End Get Set(value As Integer) sum = value End Set End Property Public Sub calcd() '該執行緒要執行的方法 For I = 0 To 1000 sum += I RaiseEvent aa(sum) '觸發事件 Threading.Thread.Sleep(100) Next End Sub End Class
接著新建一個該類別的執行個體,並設定要傳入的參數,接著設定事件的處理方式,啟動執行緒。
Public Class Form1 Private Delegate Sub InvokeDelegate(ByVal text As String) Private t As Threading.Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim c As Class1 = New Class1 '建立一個Class1的執行個體 c.Num = 10 '設定要傳入的參數(也可在建立執行個體時以建構式設定) '新建一個執行緒,指向Class1的執行個體中要執行的方法(該方法必須為Public) t = New Threading.Thread(AddressOf c.calcd) AddHandler c.ShowMsg, AddressOf ShowMsg '設定事件的處理方式,將事件指向Form1的ShowMsg() t.Start() End Sub Private Sub ShowMsg(ByVal text As String) '若呼叫端不是建立該控制項(Me)的執行緒,則以委派方式呼叫 If Me.InvokeRequired Then Invoke(New InvokeDelegate(AddressOf ShowMsg), text) Else TextBox1.Text = text '顯示訊息 End If End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click t.Abort() End Sub End Class
如此一來,每一次執行緒觸發事件時都會指向Form1的ShowMsg(),藉此傳出參數
沒有留言:
張貼留言