當我還是菜鳥程式設計師時只想把兩樣東西學好

第一樣就是物件導向的程式設計(OO)
第二樣就是多執行緒(Multithreading)

其實VB.NET的多執行緒滿好寫的…

來寫一個最簡單例子
程式資料來源(http://www.startvbdotnet.com/threading/default.aspx)

'  這類別沒什麼特別的,只是做一個簡單的For Loop加總 
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
arrow
arrow
    全站熱搜

    湯瑪的吳 發表在 痞客邦 留言(10) 人氣()