当前位置 : 主页 > 编程语言 > c语言 >

vb.net – 如何创建一个新的线程AddressOf一个带VB参数的函数?

来源:互联网 收集:自由互联 发布时间:2021-06-24
当选项严格为OFF时,工作正常. ON,我得到重载解析失败: Dim _thread1 As ThreadPrivate Sub test2(boolTest As Boolean) ' Do somethingEnd Sub'Private Sub test() _thread1 = New Thread(AddressOf test2) _thread1.Start(True)End Su
当选项严格为OFF时,工作正常. ON,我得到重载解析失败:

Dim _thread1 As Thread

Private Sub test2(boolTest As Boolean)
    ' Do something
End Sub
'
Private Sub test()
    _thread1 = New Thread(AddressOf test2)
    _thread1.Start(True)
End Sub

Overload resolution failed because no accessible ‘New’ can be called with these arguments:

‘Public Sub New(start As System.Threading.ParameterizedThreadStart)’: Option Strict On does not allow narrowing in implicit type conversions between method ‘Private Sub test2(boolTest As Boolean)’ and delegate ‘Delegate Sub ParameterizedThreadingStart(obj As Object)’.

‘Public Sub New(start As System.Threading.ThreadStart)’: Method ‘Private Sub test2(boolTest As boolean)’ does not have a signature compatible with delegate ‘Delegate Sub ThreadStart()’.

我是新线程..没有参数的函数似乎很好,但WITH参数?强硬.我怎样才能做到这一点?我已经搜索过了,大多数时候只看java / js回答这个问题.

以这种方式启动线程时,您的函数必须具有一个或多个参数.如果指定一个参数,则它必须来自Object类型.

在您的函数中,您可以简单地将此object参数转换为您的数据类型:

private sub startMe(byval param as Object)
     dim b as Boolean = CType(param, Boolean)
     ...
end sub

如果要传递多个参数,可以将它们放在一起,如下所示:

public class Parameters
     dim paramSTR as String
     dim paramINT as Integer
end class

private sub startMe(byval param as Object)
     dim p as Parameters = CType(param, Parameters)
     p.paramSTR = "foo"
     p.paramINT = 0
     ...
end sub

要开始你的线程:

dim t as new Thread(AddressOf startMe)
dim p as new Parameters
p.paramSTR = "bar"
p.oaramINT = 1337
t.start(p)
网友评论