1. 程式人生 > 實用技巧 >一例基於vb.net的跨執行緒訪問winform元件的Parallel併發程式指令碼

一例基於vb.net的跨執行緒訪問winform元件的Parallel併發程式指令碼

開發環境:vs2019

目的:測試Parallel.For併發方法

途徑:在richtextbox控制元件中列印從1到11

觀察到的現象:1到11並未按照順序輸出,因為併發操作可以並駕齊驅的執行多個任務但卻並不能保證按照順序執行

程式碼中用到了委託,因為併發執行列印數字的執行緒和渲染窗體程式的執行緒並非同一執行緒

  • 先宣告列印的原型函式
Public Sub shownumbers(ByVal i As Integer)
        RichTextBox2.Text += i.ToString() + vbCrLf
End Sub
  • 宣告原型函式的委託型別----要確保引數個數和型別與原型函式一致
Dim startwrite As delegatetowrite = New delegatetowrite(AddressOf shownumbers)
  • 把原型函式註冊到委託函式中
Dim startwrite As delegatetowrite = New delegatetowrite(AddressOf shownumbers)

  • 定義一個Action函式(在vs2019的版本中vb.net的Parallel.For()有11個版本,其中一型的函式是 Public Shared Function [For](fromInclusive As Integer, toExclusive As Integer, body As Action(Of Integer)) As ParallelLoopResult)

與此例的上級要求十分吻合,因此選用

Dim myaction As Action(Of Integer) = New Action(Of Integer)(
            Sub(ByVal i As Integer)
                RichTextBox2.Invoke(startwrite, i)
            End Sub
)
  • 呼叫Parallel.For函式
Parallel.For(1, 11, Sub(i)
           myaction(i)
End Sub)

完整的程式碼上下文

Private Sub Button4_Click(sender As
Object, e As EventArgs) Handles Button4.Click 'MessageBox.Show(shownum().ToString()) Dim watch As New Stopwatch() Dim startwrite As delegatetowrite = New delegatetowrite(AddressOf shownumbers) Dim myaction As Action(Of Integer) = New Action(Of Integer)( Sub(ByVal i As Integer) RichTextBox2.Invoke(startwrite, i) End Sub ) watch.Start() Parallel.For(1, 11, Sub(i) myaction(i) End Sub) watch.Stop() MessageBox.Show(watch.Elapsed.ToString()) End Sub Public Sub shownumbers(ByVal i As Integer) RichTextBox2.Text += i.ToString() + vbCrLf End Sub

執行效果