Another chunk of threading code today. One of the primary reasons for moving a process to a different thread is to get the load off of the primary thread. That leaves the primary thread free to refresh and paint the form while your other process works in another thread. But what happens when you need to do something on that primary thread from the new thread?
In previous examples we've been updating the text of a label. And while you can do this in Framework 1.0 and 1.1, you can't in 2.0 (note, I haven't tried this code in 2.0). And Microsoft frowns apon it. And when you try to work with more advanced objects, race conditions can occur (as I found out with a common dialog box earlier this week).
So, here is a block of code that will let you call a 'DisplayMessage' function on the form from the primary thread. When you call this method from another thread it creates a delegate and starts the call on the forms thread. I also threw in the parameter passing since this is a fairly straight forward sample.
This code sample should work in .Net v1.0, 1.1 and 2.0, but I have not tested it in v2.0.
'The public method on your form 'that you can call from any thread Public Sub DisplayMessage(ByVal Message As string) 'check if the call is coming in 'on a thread other then the one this oject 'was created in If Me.InvokeRequired Then 'Call is from a different thread 'create a delegate to call the method
'Use an object array to store the parameters Dim obj(0) As Object obj(0) = Message 'Use Begin Invoke to call this 'method on this instance's thread Me.BeginInvoke(New m_delDisplayMessage(AddressOf DisplayMessage), obj) Else 'Call is from the same thread, 'just set the text Me.StatusBar.Panels(0).Text = Message End If End Sub
'The Delegate definition for our method Private Delegate Sub m_delDisplayMessage(ByVal Message as String)