Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

An Intro to Threading 3: Crossing thread boundries (and passing parameters)

How-to

An Intro to Threading 3: Crossing thread boundries (and passing parameters)

by  ThatRickGuy  Posted    (Edited  )
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.

Code:
[color green]'The public method on your form 
'that you can call from any thread[/color]
Public Sub DisplayMessage(ByVal Message As string)
  [color green]'check if the call is coming in 
  'on a thread other then the one this oject 
  'was created in[/color]
  If Me.InvokeRequired Then
    [color green]'Call is from a different thread 
    'create a delegate to call the method

    'Use an object array to store the parameters[/color]
    Dim obj(0) As Object
    obj(0) = Message
    [color green]'Use Begin Invoke to call this 
    'method on this instance's thread[/color]
    Me.BeginInvoke(New m_delDisplayMessage(AddressOf DisplayMessage), obj)
  Else
    [color green]'Call is from the same thread, 
    'just set the text[/color]
    Me.StatusBar.Panels(0).Text = Message
  End If
End Sub

[color green]'The Delegate definition for our method[/color]
Private Delegate Sub m_delDisplayMessage(ByVal Message as String)

-Rick
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top