Passing parameters to a procedure called in thread

G

Guest

How can I pass parameters to a procedure which is called in thread?

'! Spin off a new thread.
myThread = New Thread(New ThreadStart(AddressOf GetRawFigures))
myThread.IsBackground = True
myThread.Start()

Procedure GetRawFigures takes an argument as follows:

Private Sub GetRawFigures(ByVal figures As Integer())

End Sub

When I try to provide it as

myThread = New Thread(New ThreadStart(AddressOf GetRawFigures(intArray))

I get an error saying " 'AddressOf' operand must be the name of a method; no
parentheses are needed."

How can I fix this? Thanks.
 
J

Joshua Flanagan

You cannot pass parameters to the procedure using the ThreadStart
delegate.

Instead, you could use the ThreadPool.QueueUserWorkItem, which can take
a single argument as a parameter. Note, the ThreadPool is usually
preferred over creating your own threads explicitly.

If you need to create your own thread explicitly using ThreadStart, you
need to refactor the object that contains your GetRawFigures method.
Change GetRawFigures so that it does not take any parameters, and then
add the old parameter as a property on the object.

Ex (excuse my rusty VB):

Public Class RawFigureCaller
Private myFigures as Integer()

Public New(figures as integer())
myFigures = figures
End Sub

Public Sub GetRawFigures()
'References the class-field myFigures instead of a parameter
End Sub
End Class


Now, you change the calling code to create an instance of this object
Dim caller as RawFigureCaller
'figures contains the integers you want to pass to the method
caller = new RawFiguresCaller(figures)
myThread = New Thread(New ThreadStart(AddressOf caller.GetRawFigures))


Note, you could also call GetRawFigures asynchronously AND pass it a
parameter, by using the BeginInvoke() method on a delegate that matches
your method signature (instead of creating your own thread manually).
Hmm... you might not be able to use delegates in VB.NET. I'm not sure
what the VB.NET equivalent is.

Joshua Flanagan
http://flimflan.com/blog
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top