开发环境: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
执行效果