Delegates are essentially function pointers that you can pass into a method like a parameter. This delegate is a function the called method can call back to, to perform work, to provide updates, etc.
Consider this example. Suppose I have a method that is a long-running process, and I have a status bar that I want to update. The method could take as a parameter a delegate that will get status updates that could be displayed. The code could look like this:
Delegate Sub ProcessUpdates(ByRef UpdateMessage As String)
Public Function LongRunningProcess(ByRef ProcessUpdatesDelegate As ProcessUpdates)
ProcessUpdatesDelegate.Invoke("Starting...")
' do something
ProcessUpdatesDelegate.Invoke("Step 1 Completed")
' do something
ProcessUpdatesDelegate.Invoke("Step 2 Completed")
' do something
ProcessUpdatesDelegate.Invoke("Process Completed")
End Function
Next, we would make a call into LongRunningProcess to kick it off, providing the function to call back to to process the update messages. We would do that this way:
Public Sub ProcessUpdates(ByRef UpdateMessage As String)
txtStatus.Text = UpdateMessage
End Sub
' do this somewhere in the main line code:
LongRunningProcess(AddressOf ProcessUpdates)
That's all there is to it! Notice that the signature of the ProcessUpdates method has to match the delegate signature exactly. By following this straightforward process, we can make a delegate, pass it to a method, and have the called method make calls back to the delegate as needed.
This is exactly the method we will use next time in our data access layer!
0 comments:
Post a Comment