Monday, January 16, 2006

Delegates in vb.net part III

The next item in delegates I want to cover is returning data. In my previous example we called a sub that did a task (writing out a file) but it did not return any data or notify us that we were done. To accomplish this we are going to use a delegate with a callback method.

Here is the code I am going to start with:

Private Sub StartTask()
Dim del As New DoLongTaskDelegate(AddressOf DoLongTask)
del.BeginInvoke("c:\temp.txt", Nothing, Nothing)
End Sub

Private Delegate Function DoLongTaskDelegate(ByVal filename As String) As Integer

Private Function DoLongTask(ByVal filename As String) As Integer
'do long task
Return 537
End Function

Now in order to capture the returned data we will need a method to be executed when the method completes. This method must accept an IAsyncResult as a parameter

Private Sub TaskDone(ByVal ar As IAsyncResult)
End Sub

we then change our BeginInvoke call and set the second parameter to be the AddressOf this new method:

del.BeginInvoke("c:\temp.txt", AddressOf TaskDone, del)

We set the 4th parameter to be the actuall delegate we created. We need to do this so that when the method completes we have access to the delegated method itself (remember that a delegate is basically a pointer to a methd) so that we can access its return value.

In the TaskDone method add these two lines:

Dim del As DoLongTaskDelegate = ar.AsyncState
MessageBox.Show(del.EndInvoke(ar))

The ar.AsyncState now holds the delegate we passed in when calling BeginInvoke. We then call EndInvoke on the delegate to get the result. I know how confusing this is when you start but after you play with it for a while it starts to make more sense.

0 Comments:

Post a Comment

<< Home