• 一例基于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

    执行效果

  • 相关阅读:
    vue中的组件传值
    Object中defineProperty数据描述
    promiseall的使用场景
    babel安装及使用
    checkbox属性checked="checked"已有,但却不显示打勾的解决办法
    【转载】表单验证<AngularJs>
    CSS3 :nth-child()伪类选择器
    【转载】浏览器加载和渲染html的顺序
    css制作的61种图像
    网站链接样式设置
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/13471693.html
Copyright © 2020-2023  润新知