How do I create a new AddressOf stream for a function with parameters in VB?
When strict is off, it works fine. ON, I get overload disclaimer:
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
Could not resolve the overload because "New" cannot be called with these arguments:
'Public Sub New (start As System.Threading.ParameterizedThreadStart)': Option Strict On prevents narrowing of implicit type conversions between "Private Sub test2 (boolTest As Boolean)" method and delegate "Sub ParameterizedThreadingStart Delegate (obj As Object)".
'Public Sub New (start as System.Threading.ThreadStart)': The method 'Private Sub test2 (boolTest As boolean)' does not have a signature that is compatible with the 'Delegate Sub ThreadStart ()' delegate.
I'm new to streaming. A function without parameters seems just fine, but with parameters WITH? Tough. How can i do this? I've already searched and mostly see java / js only answering this question.
When starting a thread this way, your function must have one or more parameters. If you specify one parameter, it must be of type Object
.
In your function, you can simply pass this object parameter to your datatype:
private sub startMe(byval param as Object)
dim b as Boolean = CType(param, Boolean)
...
end sub
If you want to pass multiple parameters, you can put them in a class like this:
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
To start your theme:
dim t as new Thread(AddressOf startMe)
dim p as new Parameters
p.paramSTR = "bar"
p.oaramINT = 1337
t.start(p)
source to share
You should follow al-eax's answer , but another way would be to not pass parameters in the function at all Thread.Start()
, but rather evaluate it in test
sub ...
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
... or declare it as a global variable ...
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
source to share