[VB.NET] Multithreading 遞出 Params
在以前若想要使用 multithreading,必定是使用 Threading.Thread 去操作,若是使用一般無參數函式還好,但若要操作需要 Params 的函式,可就麻煩起來了。
在網站上大多數的文章都是這樣教學的:先建立一個為 Params 設計的 Class,並在建立 Threading.Thread 時把 Params 的 Class 轉為 Object 後丟出去,而函式中則將 Object 轉為 Class去操作。
這樣的說明或許太抽象,舉個實際的例子來看看:
Public Class FmMultithreading Private Sub btnCreateThread_Click(sender As Object, e As EventArgs) Handles btnCreateThread.Click Dim bag As New Bags bag.eggs = 5 bag.user = "Yan" Debug.Print(String.Format("{0} : {1} has {2} egg(s).", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), bag.user, bag.eggs)) Dim thread As New Threading.Thread(AddressOf PickAnEgg) thread.Start(bag) End Sub Private Sub PickAnEgg(ByVal Params As Object) Dim bag As Bags = CType(Params, Bags) bag.eggs += 1 Debug.Print(String.Format("{0} : {1} has {2} egg(s).", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), bag.user, bag.eggs)) End Sub ' 程式輸出 : ' 2016/08/23 06:41:18 : Yan has 5 egg(s). ' 2016/08/23 06:41:18 : Yan has 6 egg(s). End Class Public Class Bags Public eggs As Integer = 0 Public user As String = "" End Class
這當然是一個比較簡單的例子,想樣一下,若是今天的程式用到了許多不同的執行緒且每個所傳遞的參數都不相同,一個一個量身訂做 Class 還要轉來轉去很累吧?而這裡有一個新的寫法:
Public Class FmMultithreading Private Sub btnCreateThread_Click(sender As Object, e As EventArgs) Handles btnCreateThread.Click Dim eggs As Integer = 5 Dim user As String = "Yan" Debug.Print(String.Format("{0} : {1} has {2} egg(s).", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), user, eggs)) Dim thread As New Threading.Thread(Sub() PickAnEgg(Eggs:=eggs, User:=user)) thread.Start() End Sub Private Sub PickAnEgg(ByVal Eggs As Integer, ByVal User As String) Eggs += 1 Debug.Print(String.Format("{0} : {1} has {2} egg(s).", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), User, Eggs)) End Sub ' 程式輸出 : ' 2016/08/23 06:41:18 : Yan has 5 egg(s). ' 2016/08/23 06:41:18 : Yan has 6 egg(s). End Class
如此一來,就不必再一一建立 Class 再轉來轉去,便可直接丟入 Params 囉!
留言
張貼留言