Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 如何在VB中创建带有参数的函数的新线程地址?_Vb.net_Parameters_Addressof - Fatal编程技术网

Vb.net 如何在VB中创建带有参数的函数的新线程地址?

Vb.net 如何在VB中创建带有参数的函数的新线程地址?,vb.net,parameters,addressof,Vb.net,Parameters,Addressof,当“选项严格”处于禁用状态时,工作正常。在上,我得到重载解析失败: 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 重载解析失败,因为无法使用以下参数调用可访问的“New”

当“选项严格”处于禁用状态时,工作正常。在上,我得到重载解析失败:

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
重载解析失败,因为无法使用以下参数调用可访问的“New”:

“Public Sub New(以System.Threading.ParameterizedThreadStart形式启动)”:选项Strict On不允许在方法“Private Sub test2(boolTest作为布尔值)”和委托“委托Sub ParameterizedThreadingStart(obj作为对象)”之间的隐式类型转换中缩小范围

“Public Sub New(以System.Threading.ThreadStart形式启动)”:方法“Private Sub test2(boolTest以布尔形式启动)”没有与委托“delegate Sub ThreadStart()”兼容的签名


我不熟悉穿线。。一个没有参数的函数看起来很好,但是有参数吗?很难。我该怎么做?我已经搜索过了,大部分java/js只回答了这个问题。

这似乎是因为您委托给的方法有一个布尔参数:“…不允许缩小…”将签名更改为使用对象。

以这种方式启动线程时,您的函数必须有一个或更少的参数。如果指定一个参数,则该参数必须来自类型
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)
您应该遵循,但另一种方法是根本不在
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

将来,请尝试将相关代码以及任何错误消息作为问题的一部分包含在内。您可以在仅创建一个线程时使用此选项。我不确定像bool&int这样的nativ数据类型是否是线程保存在.net中。您不应该以这种方式使用全局变量来参数化多个线程。根据MSDN,布尔值是线程安全的。您从来没有提到您想要使用多个新线程,也没有提到它们都依赖于同一个布尔参数,但是如果是这种情况,您应该遵循al-eax的答案。