ParameterizedThread in .NET 1.1
Had a problem where I wanted to run a function in a thread but it expected multiple params. So I went around making the ParameterizedThread Class which helped me to execute this method.
The Class:
Public Class ParameterizedThread
Private m_Method As [Delegate]
Public Sub New(ByVal inMethod As [Delegate])
m_Method = inMethod
End Sub
Public Sub Start(ByVal ParamArray inArgs As Object())
Dim threadClass As New InternalThreadClass(m_Method, inArgs)
Dim thread As New Threading.Thread(AddressOf threadClass.RunThread)
thread.Start()
End Sub
Private Class InternalThreadClass
Private m_Args() As Object
Private m_Method As [Delegate]
Public Sub New(ByVal inMethod As [Delegate], ByVal ParamArray inArgs As Object())
m_Method = inMethod
m_Args = inArgs
End Sub
Public Sub RunThread()
Try
m_Method.DynamicInvoke(m_Args)
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
End Class
Usage Example:
To use this class we need to create a delegate for our method. Create a new ParameterizedThread class instance and call the start method with the params the function expects.
Private Delegate Sub DoNothingDelegate(ByVal inName as String, ByVal inAge as String)
Private Sub DoNothing(ByVal inName as String, ByVal inAge as String)
' Does Nothing :)
End Sub
This is our function we would like to call and pass in the params, to do so use the following:
Dim deleg as DoNothingDelegate = AddressOf DoNothing
Dim thr as new ParameterizedThread(deleg)
' Call start passing in our params
thr.Start("bob", 22)
Issues:
There is not much checking to make sure the params match the types expected in the method. It seems to work fine for my purposes but it could be totally wrong.
Once again thanks for reading and any feedback on whether or not this will work as expected in all cases would be appreciated.
Cheers
Stefan
Update 200711151238:
I changed the class so that the args were placed in an internal class which was then called in the new thread. I thought maybe without this the state could be lost. No sure but..