Calling Synchronous Methods Asynchronously – II
In one of my previous post I talked about how to call Synchronous Methods Asynchronously using Delegates. But that was simple, because there is not return value, from that function. One of my friend has got the same problem, he want to return some status from a function, we tried this issue with the background worker class, but the problem with background worker is that we can only pass one object parameter, and if you want to pass more than one parameters, you may need to create some class / structure for that purpose and the casting issues etc. After googleing we found some alternative to do this. Here is code,
Imports System.Runtime.Remoting.Messaging 'Required for AsyncResult class.
Public Class Form1
Delegate Function longProcessDelegate(ByVal Parameter As String) As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim objlongProcessDelegate As New longProcessDelegate(AddressOf longProcess)
objlongProcessDelegate.BeginInvoke("Hello World", AddressOf Callback, Nothing)
End Sub
Private Sub Callback(ByVal ar As IAsyncResult)
Dim Result As AsyncResult = TryCast(ar, AsyncResult)
Dim objLongProc2 As longProcessDelegate = Result.AsyncDelegate
Dim msg As String = objLongProc2.EndInvoke(ar)
MessageBox.Show(msg)
End Sub
'Here I am describing the scenario with single parameter only, you can make it any number, but change the signature of the delegate also.
Private Function longProcess(ByVal Prmtr As String) As String
Threading.Thread.Sleep(5000)
Return "Updated " & Prmtr
End Function
End Class
You can get more information about Background worker and AsyncResult in MSDN
No Responses to “Calling Synchronous Methods Asynchronously – II”
RSS feed for comments on this post. TrackBack URL