如何在 VB 中创建一个带有参数的新线程 AddressOf 函数?

How can I create a new thread AddressOf a function with parameters in VB?

When option strict is OFF, works fine.打开,我遇到过载解析失败:

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()'.

我是线程的新手.. 一个没有参数的函数似乎很好,但是有参数?艰难的。我怎样才能做到这一点?我已经搜索过了,大部分看到 java/js 只回答了这个问题。

看起来是因为您要委托给的方法有一个布尔参数:“...不允许缩小...”更改签名以使用 Object。

当您以这种方式启动一个线程时,您的函数必须有一个或更少的参数。如果您指定一个参数,它必须来自 Object.

类型

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

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

当你想传递多个参数时,你可以像这样将它们组合成一个class:

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)

您应该遵循 ,但另一种方法是根本不在 Thread.Start() 函数中传递参数,而是在 test 子函数中对其求值...

Dim _thread1 As Thread

Private Sub test()
    If someTest = True then    
        _thread1 = New Thread(AddressOf test2)
        _thread1.Start()
    End If
End Sub

Private Sub test2()
    /.../
End Sub

...或者声明为全局变量...

Dim _thread1 As Thread
Dim boolTest As Boolean

Private Sub test()
    boolTest = True

    _thread1 = New Thread(AddressOf test2)
    _thread1.Start()
End Sub

Private Sub test2()
    If boolTest = True Then
        /.../
    End If
End Sub