Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

vb.net - How can I create a new thread AddressOf a function with parameters in VB?

When option strict is OFF, works fine. ON, I get overload resolution failure:

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

http://i.imgur.com/X0mH9tm.png

I'm new to threading .. a function without parameters seems just fine, but WITH parameters? Tough. How can I do this? I searched already and mostly see java/js only answering this question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you start a thread this way your function must have one or less parameters. If you specify one parameter, it must be from type Object.

In your function you can simply cast this object parameter to your datatype:

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

When you want to pass multiple parameters, you can put them together into 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 Thread:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...