WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 54 users


WorldofASP.NET >> Csharp Programming >> Delegates and Events

Delegates

Delegate is type-safe object which can point to any function to invoke them synchronously and asynchronously
Published Date : 19 May 2008
Author : Muhammad Adnan Amanullah
Language : C#
Platform : .NET
Technology : None
Views : 79357
Rating : (2 votes so far)



Calling functions/Methods synchronously & asynchronously using Delegates

Being a programmer, it’s almost daily routine to write such methods which take plenty of processor cycles/time to perform some action. For example some database operation/transactions, while using web services or Remote Procedure Calling (RPC), File I/O operations, etc.

To call such functions or methods which take plenty of time, user needs to wait for process to complete and some time in exceptional cases application hangs up if process couldn’t get complete for some reason. But in both cases user gets annoy and User Interface (UI) gets freeze until process completed if you have to call them synchronously.

In synchronous way of communication, caller process/thread needs to wait until called process/thread got complete but in case of asynchronous caller just need to send request to perform operation and get back means. It doesn’t need to wait for called process/thread completion.

Thanks to .Net team as they provide managed code Type-Safe mechanism to point any method or function and introduced Delegate. Delegates are like Function Pointer in C/C++ but Type-Safe, flexible by means of inheritance and powerful by means of referencing multiple methods as well as powerful by means of asynchronicity and supporting callback and calling them.

Delegate:

Delegate is type-safe object which can point to any function to invoke them synchronously and asynchronously. A single delegate has power to point to multiple sub routines (such functions whose return type is VOID). It invokes them at a time. Such delegates are known as Multicast delegate.  

How to define Delegate:

A delegate is quite easy to implement. Defining delegate is almost like any function as following is definition of simple function in C#.

Return_Type Function_Name(Params); //Pseudo Code

int AddTwoNumbers(int Num1, int Num2); //C# Code

And to define delegate, we just need to add delegate keyword like below:

delegate Return_Type Function_Name(Params); //Pseudo Code

delegate int AddTwoNumbers(int Num1, int Num2); //C# Code

I hope it’s easier than Rocket Science. :P


Calling method synchronously Example:

Delegates can call methods in synchronously and asynchronously manners.

Invoke method uses to call target method synchronously for same Thread.

namespace NSDelegate
{
public class HeavyProcess
{
public string GetWeatherInfo(int zip)
{
//Call weather.com web service and get information about weather}
public void MakeScriptOfDatabase()
{
//Make Database Schema and data script and write on .txt File}
}
public class MyDelegateExample
{
//Following delegate can point to those functions //which take integer value and return string valuepublic delegate string dlgGetWeatherInfo(int zip);
HeavyProcess hp = new HeavyProcess();public MyDelegateExample()
{
//Create instance of delegate and give reference of method
dlgGetWeatherInfo dlgWeatherInfo = new dlgGetWeatherInfo(hp.GetWeatherInfo);//invoke method to call referenced method/functionstring strWeatherInfo = dlgWeatherInfo.Invoke(54000);
}
}
}

Calling Method Asynchronously

BeginInvoke method used to call method asynchronously and EndInvoke methods have access on return value and input or output parameters. When we use BeginInvoke method request, it goes to queue and handles return to caller thread for proceed. Than/and target/called method would be run in another thread from thread pool. These methods would run concurrently which seems as both are running in parallel.

BeginInvoke method returns IAsyncResult which uses to pass as parameter whilst invoking EndInvoke method.

We can use two ways for determine to know that when to call EndInvoke method:

1). IAsyncResult object. We need to get WaitHandler and call WaitOne method to block execution until the WaitHandle get signal.

namespace NSDelegate
{
public class HeavyProcess
{
public string GetWeatherInfo(int zip)
{
//Call weather.com web service and get information about weather}
}
public class MyDelegateExample
{
//Following delegate can point to those functions //which take integer value and return string valuepublic delegate string dlgGetWeatherInfo(int zip);
HeavyProcess hp = new HeavyProcess();public MyDelegateExample()
{
//Create instance of delegate and give reference of method
dlgGetWeatherInfo dlgWeatherInfo = new dlgGetWeatherInfo(hp.GetWeatherInfo);//invoke method to call referenced method/functionIAsyncResult async = dlgWeatherInfo.BeginInvoke(54000, null, null);// TO DO CODE to perform any other operation// wait for the WaitHandle to be signaled.async.AsyncWaitHandle.WaitOne();//receive the resultsstring strWeatherInfo = dlgWeatherInfo.EndInvoke(async);
}
}
}

 2). Callback Delegate and Get Async State:

You might be wondering about null parameters which I have passed in BeginInvoke method in prior example code. Instead of first null parameter which I have passed, we can pass reference of another method which we want to be called automatically by the target method/thread when target method completes execution. Ins’t it better than first solution. Anyhow for that purpose we use AsyncCallback and give reference of static Method which return type is void and (takes IAsync object which return by BeginInvoke method.)

Second null parameter could be replaced by any object type data/value which used to represent state of method.

namespace NSDelegate
{
public class HeavyProcess
{
public string GetWeatherInfo(int zip)
{
//Call weather.com web service and get information about weather}
}
public class MyDelegateExample
{
//Following delegate can point to those functions //which take integer value and return string valuepublic delegate string dlgGetWeatherInfo(int zip);
HeavyProcess hp = new HeavyProcess();public MyDelegateExample()
{
//Create instance of delegate and give reference of methoddlgGetWeatherInfo dlgWeatherInfo = new dlgGetWeatherInfo(hp.GetWeatherInfo);//invoke method to call referenced method/functionIAsyncResult async = dlgWeatherInfo.BeginInvoke(54000, new AsyncCallback
(GetResultByCallback), "Did you get message? :P");
}
static void GetResultByCallback(IAsyncResult asyncResult)
{
//As we couldn't access to IAsyncResult object which we initiated in Caller //method so // we typecase and assign to keep it locally for this methodSystem.Runtime.Remoting.Messaging.AsyncResult result = 
(System.Runtime.Remoting.Messaging.AsyncResult) asyncResult;//Get control over that AsyncResult object to call its endInvoke method to //finalize async processingdlgGetWeatherInfo dlg = (System.Runtime.Remoting.Messaging.AsyncResult)result.AsyncDelegate;//receive the resultsstring strWeatherInfo = result.EndInvoke(asyncResult);//Get State result which in our case was "Did you get message? :P"string strState = (string)result.AsyncState; 
}
}
}

EndInvoke method must be called to complete delegates’ asynchronous call.

Multicast Delegate:

Power of delegate is not over at calling single method synchronously or asynchronously. Delegates can be used to call multiple methods as delegate object can have reference of multiple methods but methods return type should be void.

Internally Multicast delegates are a Link List of delegate objects and each node contains reference of prior delegate.

Delegates achieve this functionality by inheriting Multicast Delegate class under System namespace. Multicast delegates can keep or point to multiple handlers of different methods. It can be execute at single call.

Calling multiple methods at once synchronously using Multicast delegate

Covariance and Contra variance Delegates

namespace NSDelegate
{
public class HeavyProcess
{
public void MakeScriptOfDatabase()
{
//Make Database Schema and data script and write on .txt File}
public void ETW()
{
//Perform ETW Operations}
}
public class MyDelegateExample
{
//Following delegate can point to those functions //which take integer value and return string valuepublic delegate string dlgDBOperations();
HeavyProcess hp = new HeavyProcess();public MyDelegateExample()
{
//Create instance of delegate and give reference of methoddlgDBOperations dlgWeatherInfo = new dlgDBOperations(hp.MakeScriptOfDatabase);//add another function referencedlgWeatherInfo += new dlgDBOperations(hp.ETW);//Calling all referenced method/functiondlgWeatherInfo();//remove function referencedlgWeatherInfo += new dlgDBOperations(hp.ETW);//Calling all referenced method/functiondlgWeatherInfo();
}
}
}

First of all, I would like to mention here one thing very important that these features are supported from .net 2.0. Delegates are type of safe function pointers but these are very flexible and are enough powerful to support Inheritance, isn’t it cool! J

I didn’t mean here that you can make derived delegates, $ actually they support inheritance by means of return type and parameters type subclasses of the method to whom delegate refer.

Covariance deals with return type of method whereas Contra variance deals with type of parameter(s).

Covariance example

namespace NSDelegate
{
//super classpublic class Human { }
//derive class by humanpublic class Shemale : Human { }
public class MyDelegateExample
{
public delegate Human MyDelegates();static void Main()
{
//delegate pointing direct to its reference typeMyDelegates delg1 = GetHuman;//delegate pointing to subclass reference typeMyDelegates delg2 = GetShemale;
}
//instance method to create instancepublic static Human GetHuman()
{
return new Human();
}
//instance method to create instancepublic static Shemale GetShemale()
{ return new Shemale();
}
}    
}

Contravariance Example

namespace NSDelegate
{
//super classpublic class Human { }
//derive class by humanpublic class Shemale : Human { }
public class MyDelegateExample
{
public delegate Human MyDelegates();static void Main()
{
//delegate pointing direct to its reference typeMyDelegates delg1 = GetHuman;//delegate pointing to subclass reference typeMyDelegates delg2 = GetShemale;
}
//instance method to create instancepublic void   GetHuman(Human hum)
{
}
//instance method to create instancepublic void GetShemale(Shemale shem)
{ 
}
}    
}

Conclusion:

Delegate is an object which can refer to method(s) and can call methods synchornously and asynchrously (by running methods on another threads). Using asynchornous delegates, we can call time taking processes of our application like emailing, database transactions, calling web services, File I/O operations. Also can run them on different threads which doesn’t freeze UI and user doesn’t need to wait a lot.

Single Delegate can point to several methods of void return type and such kind of delegates are known as multicast delegates.

Delegates are enough flexible to support inheritence means  which can accommodate derived class of return type and parameter(s) type of referenced method. These techniques are known as covariance and contravariance which were introduced in .net 2.0.  




Other Related and Popular Articles :

Delegates and Events in C#
This article explains about delegates and Events in C#


Author Profile : Muhammad Adnan Amanullah

I am Muhammad Adnan from Pakistan (Long Live Pakistan),
Have done 4 years of computer science graduation program,
Work in .Net technolgies,
Interest lies in writing (no matter its code, article, review, tutorial and even book ;) more than reading (Even my own stuff :D)

remember in prayers :)

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

Leave New Comments


Article Content copyright by Muhammad Adnan Amanullah
Everything else Copyright © by WorldofASP.NET 2010

Category
.NET 3.5
AJAX and ATLAS
ASP.NET
C# Programming
Classic ASP
Enterprise Systems
General .NET
VB.NET Programming
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2010 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | ASP Hosting | ASP.NET Hosting | Phone Card | Calling Card |Stock Investing