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 2: Delegates

How-to

An Intro to Threading 2: Delegates

by  ThatRickGuy  Posted    (Edited  )
In the first FAQ on Multithreading (faq796-5929) we went over a basic method of launching a thread. That method was fire and forget, and we couldn't pass any values. Delegates give us a lot more power in that we can pass in parameters and use call back methods. A Call Back is a sub that is called from when the new thread ends, it is run on the calling thread which means that we can access the GUI safely from it if the thread was launched from the GUI.

Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   [color green]'first, disable the button1 object 
   'so the user can't click it again[/color]
   Button1.Enabled = False
   del = New ProcessDelegate(AddressOf Me.Process)
   Dim cb As New AsyncCallback(AddressOf Me.ProcessComplete)
   del.BeginInvoke(cb, del)
End Sub

[color green]'The Delegate definition[/color]
Protected Delegate Sub ProcessDelegate()

[color green]'The delegate that will launch the 
'process[/color]
Protected del As ProcessDelegate

[color green]'The Callback method the will launch 
'in the original thread when the thread 
'completes[/color]
Protected Sub ProcessComplete(ByVal ar As System.IAsyncResult)
  me.button1.enabled = true
end sub

[color green]'The long process[/color]
Protected Sub Process()
   For a As Integer = 1 To 10
      For b As Integer = 1 To 100000000
         [color green]'do something really 
         'important here[/color]
      Next
      [color green]'simulate a progress bar 
      '(This stuff should be handled in a 
      'thread safe manor, but this will 
      'work pre-2k5)[/color]
      Label2.Text = a.ToString
      Label2.Refresh()
   Next
End Sub

-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