Friday, June 25, 2010

WCF Concurrency (Single, Multiple and Reentrant) and Throttling

Introduction and Goal
Pre-requisite
Why do we need concurrency in WCF?
WCF concurrency and instancing – two different things
Three types of WCF concurrency
By default WCF services are Single concurrency – Sample code demonstration
9 combinations of Instancing and Concurrency
Instance mode = Per Call and Concurrency = Single
Instance mode = per Call and Concurrency = Multiple
Instance mode = per session and Concurrency = single
Instance mode = per session and Concurrency = Multiple
Instance mode = Single and Concurrency = Single
Instance mode = Single and Concurrency = Multiple
Reentrant
Throttling behavior
Default values for WCF throttling
Reference

Introduction and Goal

In this article we will concentrate on WCF concurrency and throttling. We will first try to understand what are WCF concurrency and the 3 important types of WCF concurrency. We will then see a small sample of WCF concurrency with single and multiple. We will then go through 9 combinations of WCF concurrency and instancing. Finally we will try to understand how to configure throttling using WCF ‘web.config’ file.

This is a small Ebook for all my .NET friends which covers topics like WCF,WPF,WWF,Ajax,Core .NET,SQL,Design patterns , UML , Azure etc you can download the same from here or else you can catch me on my daily free training @ from here


Courtesy: - http://www.nassaulibrary.org/ncla/nclacler_files/LILC7.JPG

Pre-requisite


In order to understand WCF concurrency well, it’s important to understand concepts around WCF instancing. So before moving ahead with this article please do once read WCF instancing from here

Why do we need concurrency in WCF?


If you search on the web for the dictionary meaning of concurrency you will find the following definition:-
“Happening at the same time”

WCF concurrency helps us to configure how WCF service instances can serve multiple requests at the same time. You will need WCF concurrency for the below prime reasons, there can be other reasons as well but these stand out as important reasons:-

Increase through put: - Many times you want to increase the amount of work your WCF service instance does at any moment of time, in other words you would like to increase the through put. Throughput means how much work a given thing can do. By default WCF service handles only one request at given moment of time.

Integration with legacy system: - Many times your WCF services interact with legacy systems like VB6 COM etc. It’s very much possible that these systems are not multithreaded, in other words they handle only one request at any given moment of time. So even though your WCF service has concurrent capabilities you would like still to handle one request at a one time. This is achieved by using throttling in combination with WCF concurrency capabilities.

WCF concurrency and instancing – two different things

In our previous article we had discussed about WCF instances. WCF instancing and WCF concurrency are two different things. WCF instance dictates how the objects are created while WCF concurrency dictates how many requests can be handled by the WCF objects. I do understand that many of our developer’s friends know this difference, but as you go deeper in WCF concurrency there is lot of connection with WCF instancing also, so wanted to just emphasize the differences.

WCF instancing gives three levels of WCF object instance controls per call, per session and single. In case you are not aware of the same do read my article 3 way to do WCF instance management . In similar lines WCF concurrency also have 3 ways of implementing WCF concurrency.

Three types of WCF concurrency

There are three ways by which you can handle concurrency in WCF Single, multiple and reentrant. To specify WCF concurrency we need to use the ‘ServiceBehavior’ tag as shown below with appropriate ‘ConCurrencyMode’ property value.


Single: - A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is not completed.

Multiple: - In this scenario multiple requests can be handled by the WCF service object at any given moment of time. In other words request are processed at the same time by spawning multiple threads on the WCF server object.
So you have great a throughput here but you need to ensure concurrency issues related to WCF server objects.

Reentrant: - A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call WCF client through callback and reenter without deadlock.



By default WCF services are Single concurrency – Sample code demonstration

By default WCF services are set to concurrency type ‘single’ and instancing mode ‘per call’. In order to demonstrate the same, let’s create a simple sample code as shown below. We will create a simple WCF service with a method name called as ‘Call’. When any client calls this WCF service it will display the
following details:-
• Client name that made the call. This value will be provided as an input when the client wants to make call to the WCF service.
• Instance number, this will represent number of WCF instance count which is serving the request.
• Thread number which is executing the method.
• Time when the ‘Call’ method was actually called.

Below is the service contract of the ‘Call’ method. Please note that the ‘OperationContract’ is defined as ‘IsOneWay’ true.
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract(IsOneWay=true)]
void Call(string ClientName);
}
Below is the simple implementation of the service contract ‘IHelloWorldService’ interface defined below. It has a instance variable ‘i’ which helps us to maintain the instance counter and simple console.writeline which displays client name, instance number , thread number and time when the
method was called.
This method waits for 5 seconds using the ‘Thread.Sleep’ function.
public class HelloWorldService : IHelloWorldService
{
// maintain instance count
public int i;
public void Call(string ClientName)
{
// increment instance counts
i++;

// display client name, instance number , thread number and time when
// the method was called

Console.WriteLine("Client name :" + ClientName + " Instance:" + i.ToString() + " Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + " Time:" + DateTime.Now.ToString() + "\n\n");

// Wait for 5 seconds
Thread.Sleep(5000);
}}




This WCF service will be self hosted using ‘WsHttpBinding’ as shown below. We have chosen self hosting so that we can monitor the time, threads and number of
instances of WCF service.

static void Main(string[] args)
{
//Create a URI to serve as the base address
Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");

//Create ServiceHost
ServiceHost host = new ServiceHost(typeof(ClassLibrary1.HelloWorldService), httpUrl);

//Add a service endpoint
host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService), new WSHttpBinding(), "");

//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);

//Start the Service
host.Open();

Console.WriteLine("Service is host at " + DateTime.Now.ToString());
Console.WriteLine("Host is running... Press <Enter> key to stop");
Console.ReadLine();
}


From the client side we will make 5 continuous calls simultaneously on the WCF service. Below is the code snippet for the same.
Console.WriteLine("Enter Client name");
string str = Console.ReadLine();
ServiceReference1.HelloWorldServiceClient obj = new ServiceReference1.HelloWorldServiceClient();

for(int i=0;i<5;i++)
{
obj.Call(str);
}

If you run the above project and monitor your WCF server service you will see the screen shot. There are 2 important points to note:-

• By default the WCF service is configure to run with instance mode of per call. So new instances are created every time the service runs. Instance 1, 2, 3 and 4 indicate new instances created for every method call.
• By default the concurrency is single so same thread is use to service all the 5 request’s which are sent from the WCF client side. You can see the value of the thread is always 4.
• The most important factor is time. As the concurrency is configured as single it will be called one after another sequentially. You can notice the same from the time difference of method call of 5 seconds.

Let’s go and change the concurrency mode to multiple. In order to change the concurrency mode to multiple we need to specify ‘Multiple’ in the concurrency mode as shown in the below code snippet.


If you run the client now you can see different threads (i.e. thread 4, 5, 6, 7 and 8) are spawned to serve the request and the time of the method calls are almost same. In other words the methods are executed concurrently on different threads.

In short you are now having higher throughput in less amount of time.

9 combinations of Instancing and Concurrency


There are 9 combination of concurrency and instancing methodology as shown in the below table. In the further coming section we will discuss in more detail about the same.

Instance mode = Per Call and Concurrency = Single
Instance mode ‘PerCall’ with ‘Single’ concurrency is the default setting in WCF. We have already seen and example and demonstration of the same.

With per call new WCF instances are created for every method calls made to the WCF server service. The default concurrency is single so only one thread will be used to serve all instances
Below is a simple pictorial representation of what will happen in per call and single concurrency scenario:-

• For every client instance a single thread will be allocated.
• For every method call a new service instance will be created.
• A single thread will be used to serve all WCF instances generated from a single client instance.



If you refer the previous sample you can see how threads are same and the halt of 5 seconds on the WCF service.


Instance mode = per Call and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
{
}


In this combination multiple instances are created for every call but multiple threads serve every method call to WCF service instance. You can see in
the below figure we have two WCF service instance and every instance has multiple WCF service objects created for every method call. Every method call is handled by multiple threads.

In the above sample if you remember we have multiple threads serving every method call and the time difference between every method call is reduced considerably. The method calls are fired approximately same time.

Instance mode = per session and Concurrency = single

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
{
}


In this combination one WCF service instance is created for every WCF client session because the WCF instance mode is set to per session. All the method
calls are executed in a sequential manner one by one. In other words only one thread is available for all method calls for a particular service instance.

If you run the sample code with the per session and single combination mode you will find the same thread executes all request with same WCF instance per session.


Instance mode = per session and Concurrency = Multiple


[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
{
}


In this combination one WCF instance is created for every WCF client session and every method call is run over multiple threads. Below is the pictorial
representation of the same.


If you run the sample code attached with this article you will find same instance with every method call running on different methods.


To get a better idea you can run with different client exe instance with different names as shown below. You can notice how every client get his own WCF service instance with every method allocated to run on different threads.


Instance mode = Single and Concurrency = Single


[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
{
}

In this combination only one instance of WCF service instance is created which serves all requests which are sent from all WCF clients. These entire
requests are served using only one thread.

You can see in the below figure approximately one thread is assigned for every WCF client call and only one instance of the WCF service is created.

Instance mode = Single and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
{}

In this combination one WCF service instance is created for serve all WCF clients. All request are served using multiple / different threads.

You can see from the output we have 6 threads serving 10 requests as compared previously we had approximately only 2 threads.

Reentrant

In mode only thread runs to serve all requests. If your WCF service makes an outbound call to some other WCF service or makes a client call it releases the thread lock. In other words until the outbound call is completed other WCF clients can make call.


Throttling behavior


WCF throttling settings helps you to put an upper limit on number of concurrent calls, WCF instances and concurrent session. WCF provides 3 ways by which you can define upper limits MaxConcurrentCalls, MaxConcurrentInstances and MaxConcurrentSessions.

MaxConcurrentCalls: - Limits the number of concurrent requests that can be processed by WCF service instances.
MaxConcurrentInstances: - Limits the number of service instances that can be allocated at a given time. When it’s a PerCall services, this value matches the number of concurrent calls. For PerSession services, this value equals the number of active session instances. This setting doesn’t matter for Single instancing mode, because only one instance is ever created.
MaxConcurrentSessions: - Limits the number of active sessions allowed for the service.
All the above 3 setting can be defined in the ‘servicebehaviors’ tag as shown in the below XML snippet.

<serviceBehaviors>

<behavior name="serviceBehavior">

<serviceThrottling maxConcurrentCalls="16"

maxConcurrentInstances="2147483647" maxConcurrentSessions="10" />

</behavior>

</serviceBehaviors>


Default values for WCF throttling


Below is a simple table which shows default settings for throttling as per different WCF versions.



Reference
Nice information on throttling details by Mr. Kenny wolf http://kennyw.com/work/indigo/150

Nice article by Mr. Rick Rain in 3 parts which explains Concurrency and throttling in depth.
http://blogs.msdn.com/b/rickrain/archive/2009/06/15/wcf-instancing-concurrency-and-throttling-part-1.aspx


Mr. Michele Leroux Bustamante talks about settings which influence how throughput of WCF services can be increased using WCF concurrency.
http://www.windowsitpro.com/article/net-framework2/concurrency-and-throttling-configurations-for-wcf-services.aspx


Justin smith explains demonstrates a sample code on how ‘InstanceContextMode’ and ‘ConcurrencyMode’ property affects concurrency.
http://www.wintellect.com/CS/blogs/jsmith/archive/2006/05/16/instancecontextmode-and-concurrencymode.aspx


Mr. Glav talks about throttling and legacy system http://weblogs.asp.net/pglavich/archive/2007/06/27/wcf-and-concurrent-usage-throttling.aspx

Default values for WCF throttling
http://blogs.msdn.com/b/wenlong/archive/2009/07/26/wcf-4-higher-default-throttling-settings-for-wcf-services.aspx

Sunday, June 6, 2010

3 ways to do WCF instance management (Per call, Per session and Single)


Introduction
WCF service object instancing basics
Per Call instance mode
How to implement WCF per call instancing?
Per session Instance mode
How to implement per session Instancing?
Single Instance mode
How to implement Single Instance mode?
When should you use per call, per session and single mode?
Per call
Per session
Single
References

Introduction

Many times we would like to control the way WCF service objects are instantiated on WCF server. You would like to control how long the WCF instances should be residing on the server.

WCF framework has provided 3 ways by which we can control the WCF instance creation. In this article we will first try to understand those 3 ways of WCF service instance control with simple code samples of how to achieve them. Finally we will compare when to use under what situations.

This is a small Ebook for all my .NET friends which covers topics like WCF,WPF,WWF,Ajax,Core .NET,SQL etc you can download the same from http://tinyurl.com/4nvp9t or else you can catch me on my daily free training @ http://tinyurl.com/y4mbsn6

WCF service object instancing basics

In a normal WCF request and response communication following sequence of actions takes place:-
• WCF client makes a request to WCF service object.
• WCF service object is instantiated.
• WCF service instance serves the request and sends the response to the WCF client.

Following is the pictorial representation of how WCF request and response work.



Following are different ways by which you would like to create WCF instances:-
• You would like to create new WCF service instance on every WCF client method call.
• Only one WCF service instance should be created for every WCF client session.
• Only one global WCF service instance should be created for all WCF clients.
To meet the above scenarios WCF has provided 3 ways by which you can control WCF service instances:-
• Per Call
• Per session
• Single instance

Per Call instance mode

When we configure WCF service as per call, new service instances are created for every method call you make via WCF proxy client. Below image shows the same in a pictorial format:-

• WCF client makes first method call (method call 1).
• New WCF service instance is created on the server for this method call.
• WCF service serves the request and sends response and the WCF instance is destroyed and given to garbage collector for clean up.
• Now let’s say WCF client makes a second method call, again a new instance is created, request is served and the WCF instance is destroyed.

In other words for every WCF client method call one WCF service instance is created and destroyed once the request is served.



How to implement WCF per call instancing?

In order to specify instancing mode we need to provide ‘InstanceContextMode’ value in the ‘ServiceBehavior’ attribute as shown below. This attribute we need to specify on the ‘Service’ class. In the below code snippet we have specified ‘intCounter’ as a class level variable as shown below and the class counter is incremented by one when method ‘Increment’ is called.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)]
public class Service : IService
{
private int intCounter;

public int Increment()
{
intCounter++
return intCounter;
}
}
At the client we have consumed the WCF client and we have called ‘Increment’ method twice.
ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
MessageBox.Show(obj.Increment().ToString());
MessageBox.Show(obj.Increment().ToString());
Even though we have called the ‘Increment’ method twice we get value ‘1’. In other words the WCF service instance is created for every method call made to the WCF service instance so the value will always be one.


Per session Instance mode


Many times we would like to maintain state between method calls or for a particular session. For those kind of scenarios we will need to configure the service as per session. In per session only one instance of WCF service object is created for a session interaction. Below figure explains the same in a pictorial format.

• Client creates the proxy of WCF service and makes method calls.
• One WCF service instance is created which serves the method response.
• Client makes one more method call in the same session.
• The same WCF service instance serves the method call.
• When client finishes his activity the WCF instance is destroyed and served to garbage collector for clean up.

How to implement per session Instancing?


To configure service as per session we need to configure ‘ServiceBehavior’ attribute with ‘PerSession’ value in the ‘InstanceContextMode’ object.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService
{
private int intCounter;
public int Increment()
{
intCounter++
return intCounter;
}}


At the client side when we run the below client code. You should see the value as ‘2’ after the final client code is executed. We have called the method
twice so the value will be seen as two.
ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient();
MessageBox.Show(obj.Increment().ToString());
MessageBox.Show(obj.Increment().ToString());




Single Instance mode


Many times we would like to create one global WCF instance for all WCF clients. To create one single instance of WCF service we need to configure the WCF service as ‘Single’ instance mode. Below is a simple pictorial notation of how single instance mode will operate:-

• WCF client 1 requests a method call on WCF service.
• WCF service instance is created and the request is served. WCF service instance is not destroyed the service instance is persisted to server other requests.
• Now let’s say some other WCF client i.e. client 2 requests a method call.
• The same WCF instance which was created by WCF client 1 is used to serve the request of WCF client 2. In other words only one global WCF server service instance is created to serve all client requests.

How to implement Single Instance mode?

In order to create a single instance of WCF service we need to specify the‘InstanceContextMode’ as ‘Single’.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Service : IService
{
}

If you call the WCF from different client you will see the counter keep incrementing. The counter has become a global variable.


When should you use per call, per session and single mode?


Per call



• You want a stateless services
• Your service hold intensive resources like connection object and huge memory
objects.
• Scalability is a prime requirement. You would like to have scale out
architecture.
• Your WCF functions are called in a single threaded model.

Per session



• You want to maintain states between WCF calls.
• You want ok with a Scale up architecture.
• Light resource references

Single




• You want share global data through your WCF service.
• Scalability is not a concern.

References


MSDN link for WCF instances
http://msdn.microsoft.com/en-us/library/ms733040.aspx

Do not miss this post which covers end to end about WCF sessions
http://codeidol.com/csharp/wcf/Instance-Management/

Great blog by Rick rain on WCF instancing
http://blogs.msdn.com/b/rickrain/archive/2009/06/15/wcf-instancing-concurrency-and-throttling-part-1.aspx

Wednesday, June 2, 2010

6 important uses of Delegates and Events

Introduction

In this article we will first try to understand what problem delegate solves, we will then create a simple delegate and try to solve the problem. Next we will try to understand the concept of multicast delegates and how events help to encapsulate delegates. Finally we understand the difference between events and delegates and also understand how to do invoke delegates asynchronously.

Once we are done with all fundamentals we will summarize the six important uses of delegates.

This is a small Ebook for all my .NET friends which covers topics like WCF,WPF,WWF,Ajax,Core .NET,SQL etc you can download the same from http://tinyurl.com/4nvp9t
or else you can catch me on my daily free training @ http://tinyurl.com/39m4ovr

Abstraction problems of methods and functions

Before we move ahead and we talk about delegates let’s try to understand what problem does delegate solve. Below is a simple class named ‘ClsMaths’ which has a simple ‘Add’ function. This class ‘ClsMaths’ is consumed by a simple UI client. Now let’s say over a period of time you add subtraction functionality to the ‘ClsMaths’ class, your client need to change accordingly to accommodate the new functionality.

In other words addition of new functionality in the class leads to recompiling of your UI client.



In short the problem is that there is a tight coupling of function names with the UI client. So how can we solve this problem?. Rather than referring to the actual methods in the UI / client if we can refer an abstract pointer which in turn refers to the methods then we can decouple the functions from UI.

Later any change in the class ‘ClsMath’ will not affect the UI as the changes will be decoupled by the Abstract pointer. This abstract pointer can be defined by using delegates. Delegates define a simple abstract pointer to the function / method.


Ok, now that we have understood the tight coupling problem and also the solution, let’s try to understand how we can define a simple delegate.

How to declare a delegate?


To implement a delegate is a four step process declare, create, point and invoke.

The first step is to declare the delegate with the same return type and input parameters. For instance the below function ‘add’ has two input integer parameters and one integer output parameter.
private int Add(int i,int y)
{
return i + y;
}

So for the above method the delegate needs to be defined in the follow manner below. Please see the delegate keyword attached with the code.
// Declare delegate
public delegate int PointetoAddFunction(int i,int y);
The return type and input type of the delegate needs to be compatible, in
case they are not compatible it will show the below error as shown in the image
below.

The next step (second step) is to create a delegate reference.
// Create delegate reference
PointetoAddFunction myptr = null;
The third step is to point the delegate reference to the method, currently we
need to point the delegate reference to the add function.

// Point the reference to the add method
myptr = this.Add;
Finally we need to invoke the delegate function using the “Invoke” function
of the delegate.
// Invoke the delegate
myptr.Invoke(20, 10)
Below figure sums up how the above four step are map with the code snippet.



Solving the abstract pointer problem using delegates

In order to decouple the algorithm changes we can expose all the below arithmetic function through an abstract delegate.


So the first step is to add a generic delegate which gives one output and takes two inputs as shown in the below code snippet.
public class clsMaths
{
public delegate int PointerMaths(int i, int y);
}



The next step is to expose a function which takes in operation and exposes an attached delegate to the UI as shown in the below code snippet.
public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}
}


Below is how the complete code snippet looks like. All the algorithm functions i.e. ‘Add’ , ‘Sub’ etc are made private and only one generic abstract
delegate pointer is exposed which can be used to invoke these algorithm function.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}

private int Add(int i, int y)
{
return i + y;
}
private int Sub(int i, int y)
{
return i - y;
}
private int Multi(int i, int y)
{
return i * y;
}
private int Div(int i, int y)
{
return i / y;
}
}


So at the client side the calls becomes generic without any coupling with the actual method names like ‘Add’ , ‘Sub’ etc.
int intResult = objMath.getPointer(intOPeration).Invoke(intNumber1,intNumber2);

Multicast delegates

In our previous example we have see how we can create a delegate pointer to a function or method. We can also create a delegate which can point to multiple functions and methods. If we invoke such delegate it will invoke all the methods and functions associated with the same one after another sequentially.

Below is the code snippet which attaches 2 methods i.e. method1 and method2 with delegate ‘delegateptr’. In order to add multiple methods and function we need to use ‘+=’ symbols. Now if we invoke the delegate it will invoke ‘Method1’ first and then ‘Method2’. Invocation happen in the same sequence as the attachment is done.
// Associate method1
delegateptr += Method1;
// Associate Method2
delegateptr += Method2;
// Invoke the Method1 and Method2 sequentially
delegateptr.Invoke();


So how we can use multicast delegate in actual projects. Many times we want to create publisher / subscriber kind of model. For instance in an application
we can have various error logging routine and as soon as error happens in a application you would like to broadcast the errors to the respective components.



Simple demonstration of multicast delegates

In order to understand multicast delegates better let’s do the below demo. In this demo we have ‘Form1’, ‘Form2’ and ‘Form3’. ‘Form1’ has a multicast delegate which will propagate event to ‘Form2’ and ‘Form3’.



At the form level of ‘Form1’ (this form will be propagating events to form2 and form3) we will first define a simple delegate and reference of the delegate as shown in the code snippet below. This delegate will be responsible for broadcasting events to the other forms.

// Create a simple delegate
public delegate void CallEveryOne();

// Create a reference to the delegate
public CallEveryOne ptrcall=null;
// Create objects of both forms

public Form2 obj= new Form2();
public Form3 obj1= new Form3();


In the form load we invoke the forms and attach ‘CallMe’ method which is present in both the forms in a multicast fashion ( += ).
private void Form1_Load(object sender, EventArgs e)
{
// Show both the forms
obj.Show();
obj1.Show();
// Attach the form methods where you will make call back
ptrcall += obj.CallMe;
ptrcall += obj1.CallMe;
}


Finally we can invoke and broadcast method calls to both the forms.
private void button1_Click(object sender, EventArgs e)
{
// Invoke the delegate
ptrcall.Invoke();
}


Problem with multicast delegates – naked exposure

The first problem with above code is that the subscribers (form2 and form3) do not have the rights to say that they are interested or not interested in the events. It’s all decided by ‘form1’.

We can go other route i.e. pass the delegate to the subscribers and let them attach their methods if they wish to subscribe to the broadcast sent by ‘form1’. But that leads to a different set of problems i.e. encapsulation violation.

If we expose the delegate to the subscriber he can invoke delegate, add his own functions etc. In other words the delegate is completely naked to the subscriber.



Events – Encapsulation on delegates

Events help to solve the delegate encapsulation problem. Events sit on top of delegates and provide encapsulation so that the destination source can only listen and not have full control of the delegate object.
Below figure shows how the things look like:-
• Method and functions are abstracted /encapsulated using delegates
• Delegates are further extended to provide broadcasting model by using multicast delegate.
• Multicast delegate are further encapsulated using events.



Implementing events

So let’s take the same example which we did using multicast delegates and try to implement the same using events. Event uses delegate internally as event provides higher level of encapsulation over delegates.

So the first step in the publisher (‘Form1’) we need to define the delegate and the event for the delegate. Below is the code snippet for the same and please do notice the ‘event’ keyword.

We have defined a delegate ‘CallEveryOne’ and we have specified an event object
for the delegate called as ‘EventCallEveryOne’.
public delegate void CallEveryone();
public event CallEveryone EventCallEveryOne;


From the publisher i.e. ‘Form1’ create ‘Form2’ and ‘Form3’ objects and attach the current ‘Form1’ object so that ‘Form2’ and ‘Form3’ will listen to the
events. Once the object is attached raise the events.
Form2 obj = new Form2();
obj.obj = this;
Form3 obj1 = new Form3();
obj1.obj = this;
obj.Show();
obj1.Show();
EventCallEveryOne();


At the subscriber side i.e. (Form2 and Form3) attach the method to the event
listener.
obj.EventCallEveryOne += Callme;


This code will show the same results as we have got from multicast delegate
example.

Difference between delegates and events

So what’s really the difference between delegates and events other than the sugar coated syntax of events. As already demonstrated previously the main difference is that event provides one more level of encapsulation over delegates.

So when we pass delegates it’s naked and the destination / subscriber can modify the delegate. When we use events the destination can only listen to it.



Delegates for Asynchronous method calls


One of the other uses of delegates is asynchronous method calls. You can call methods and functions pointed by delegate asynchronously.

Asynchronous calling means the client calls the delegate and the control is returned back immediately for further execution. The delegate runs in parallel to the main caller. When the delegate has finished doing his work he makes a call back to the caller intimating that the function / subroutine has completed executing.


To invoke a delegate asynchronously we need call the ‘begininvoke’ method. In
the ‘begininvoke’ method we need to specify the call back method which is
‘CallbackMethod’ currently.
delegateptr.BeginInvoke(new AsyncCallback(CallbackMethod), delegateptr);


Below is the code snippet for ‘CallbackMethod’. This method will be called
once the delegate finishes his task.
static void CallbackMethod(IAsyncResult result)
{
int returnValue = flusher.EndInvoke(result);
}


Summarizing Use of delegates

There are 6 important uses of delegates:-

1. Abstract and encapsulate a method (Anonymous invocation)
This is the most important use of delegates; it helps us to define an abstract
pointer which can point to methods and functions. The same abstract delegate can
be later used to point to that type of functions and methods. In the previous
section we have shown a simple example of a maths class. Later addition of new
algorithm functions does not affect the UI code.
2. Callback mechanismMany times we would like to provide a call back mechanism. Delegates can be
passed to the destination and destination can use the same delegate pointer to
make callbacks.
3. Asynchronous processingBy using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously.
In our previous section we have explained the same in detail.
4. Multicasting - Sequential processingSome time we would like to call some methods in a sequential manner which
can be done by using multicast delegate. This is already explained in the
multicast example shown above.
5. Events - Publisher subscriber model
We can use events to create a pure publisher / subscriber model.

Difference between delegates and C++ pointer

C++ pointers are not type safe, in other words it can point to any type of
method. On the other hand delegates are type safe. A delegate which is point to
a return type of int cannot point to a return type of string.