2010年9月7日 星期二

在vb.net下寫多執行緒的程式

原文處
Public Class Count1
Public CountTo as Integer
' 當程序處理完畢,透過這個method來讓對方知道你已經做完了
Public event FinishedCounting(ByVal NumberOfMatches as Integer)
Sub Count()
Dim ind,tot as Integer
tot=0
For ind=1 to CountTo
tot+=1
Next ind
' raise一個事件出來說已經做完了
' 並將處理完的值回傳回去
RaiseEvent FinishedCounting(tot)
End Sub
End Class

' 這一段程式碼就是用來執行呼叫thread
Dim counter1 as new Count1()
Dim Thread1 as New System.Threading.Thread(Addressof counter1.Count)
Private Sub LetMeCallThread(Byval counter as Integer)
counter1.CountTo=counter
' 與物件之間的Call Back機制, 建立handler (Call Back的function)
' 當物件Raise該事件時,可以透過該function取得結果
AddHandler counter1.FinishedCounting,AddressOf FinishedCountingEventHandler
' 啟動執行緖
Thread1.Start()
End Sub

' 當Thread程式執行完畢(這就是所謂的CallBack機制)
Sub FinishedCountingEventHandler(ByVal Count as Integer)
msgbox(Count)
End Sub

沒有留言:

張貼留言