dotnet thoughts 

a dotnet developer's technical blog

Generic delegates in .Net 3.5

In my previous post I talked about Calling Synchronous methods asynchronously using delegates. But while working with .Net 3.5, there are few new concepts like Generic delegates, which helps you to call the methods asynchronously without creating a delegate.

Code using action delegate, which can be used for methods, which doesn’t returns anything


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim c As New Action(Of String)(AddressOf LongProcess)
c.BeginInvoke("Hello", Nothing, Nothing)
End Sub
Sub LongProcess(ByVal Msg As String)
Threading.Thread.Sleep(5000)
MessageBox.Show(Msg)
End Sub
End Class

You can find more information about this on MSDN : Action generic delegate and Func generic delegate

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