Asynchronous Requests, Threading and Delegates in .NET

I get lots of questions here at GE Healthcare from other developers on the subject of threading. We are still on 1.1 of the Framework which does not have the backgroundworker component. This is what I usually provide as an example to them to help them understand and acomplish this.
 
For this example here though I made use of some 2.0 Framework technology. So its useful to you as well if you are lucky enough to be current in your framework.
 
' Here you have a function that already exists.  Now you want to'
' be able to run it in a separate thread.'
    Function RandomFunction(ByVal Param1 As String, ByVal Param2 As Object, ByVal param3() As Integer) As List(Of String)
        Return Nothing
    End Function
 
' So we declare a delegate with a matching signature'
    Delegate Function RandomFunctionDelegate(ByVal Param1 As String, ByVal Param2 As Object, ByVal param3() As Integer) As List(Of String)
' Create an instance of the delegate that points to our original method'
    Dim RandomFunctionDelagteInstance As New RandomFunctionDelegate(AddressOf RandomFunction)
' And create a place to store the return value.'
    Dim RandomFunctionReturnValue As List(Of String)
' Now we can create a simple new method that kicks off the old method asynchronously.'
    Sub RandomFunctionBegin(ByVal Param1 As String, ByVal Param2 As Object, ByVal param3() As Integer)
' The BeginInvoke() method is part of every delegate.'
' Here we want to tell it what code to run when the method is finished.'
        RandomFunctionDelagteInstance.BeginInvoke(Param1, Param2, param3, AddressOf RandomFunctionEnd, Nothing)
    End Sub
'And finally, here is how we know when it finishes and set the return value.'
    Sub RandomFunctionEnd(ByVal ar As IAsyncResult)
        RandomFunctionReturnValue = RandomFunctionDelagteInstance.EndInvoke(ar)
    End Sub

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: