加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

VB.NET多线程编程参数的传递以及返回值的获取

发布时间:2020-12-17 08:11:26 所属栏目:百科 来源:网络整理
导读:下面的例子是使用多线程同时弹出4个msgbox ———————————————— 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Imports System.Threading Public Class Form1 Structure MyParameters Dim nNum As Integer End Structure Public p

下面的例子是使用多线程同时弹出4个msgbox


————————————————

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Imports System.Threading
Public Class Form1
Structure MyParameters
Dim nNum As Integer
End Structure
Public paramPM(3) As MyParameters
Public Function sPM2( ByVal paramPM As MyParameters) As String
MessageBox.Show( "Hello" +paramPM.nNum.ToString())
Return ""
End Function
Private Sub Button1_Click( ByVal sender As System. Object , ByVal e As System.EventArgs) Handles Button1.Click
ThreadPool.QueueUserWorkItem( New WaitCallback( AddressOf sPM2),paramPM(0))
ThreadPool.QueueUserWorkItem( New WaitCallback( AddressOf sPM2),paramPM(1))
ThreadPool.QueueUserWorkItem( New WaitCallback( AddressOf sPM2),paramPM(2))
ThreadPool.QueueUserWorkItem( New WaitCallback( AddressOf sPM2),paramPM(3))
End Sub
End Class

VB.NET中多线程编程非常容易方便,只要 Dim MyThread as new system.Threading.Thread(Addressof MySub)就可以了,其中MySub是多线程中要运行的处理过程。但是如果要向线程中传递参数或者要获取线程的返回值,就不是很方便了。当然我们可以通过定义全局变量,但这会使程序的维护变得困难,增加系统开销,甚至会因线程间的并发操作导致无法预料的结果。
笔者通常采用的方法是定义一个类。在类中定义几个私有变量,用于存放参数。再定义一个带参数的构造过程,所带的参数就是我们要们要向线程中传递的参数(形参)。在构造过程中,把参数传给私有变量。再定义一个在线程中要使用的处理过程,在处理过程中就可以随意的使用私有变量来得到所需的参数。
至于返回值,可以在类中定义一个带参数的事件,在处理参数中触发事件,并把我们所需要的返回值做为参数传递出去。


在构建多线程时,先 Private WithEvents MyFirstClass as new MyClass(Arg1,Arg2....)其中Arg1,Arg2...就是我们要向线程中传递的参数(实参),然后再Dim MyThread as New System.Threading.Thread(Addressof MyFirstClass.MySub))就可以了。


在事件过程MyFirstClass_MyEvent(nReturn)中,通过nReturn就可以得到我们所要的返回值了。

代码示例:
1、类模块代码:
Public Class MyClass
dim MyArg1 as Integer
Dim MyArg2 as Integer

sub New(Byval Arg1 as Integer,Byval Arg2 as Integer)
MyArg1=Arg1
MyArg2=Arg2
End Sub

public Event MyEvent(Byval nReturn as Integer)


Public Sub MySub
Dim MyReturn as Integer=MyArg1 + MyArg2
RaiseEvent MyEvent(MyReturn)
End Sub
End Class

2、窗口模块代码:

Public Class From1
Private WithEvent MyFirstClass as New MyClass(1,3)


Private Sub MyFirstClass_MyEvent(Byval nReturn as Integer) Handles MyFirstClass.MyEvent

'nReturn中就是返回值

End Sub

本例为了抛砖引玉,只是向线程中传递两个整型参数1、3,然后在处理过程中简单将两个数相加,最后返回结果。在实际使用中当然要复杂的多。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读