Pages

Men

rh

6/16/2012

Delegates and Events

Delegate is user define type. Using delegates we can pass method as a parameter. Delegates are type safe. If you want to pass method as a parameter, the signature of the method must matches with signature of the delegate

Example:

public delegate double Delegate_Test(int a, int b);
Class Test
{
   Static double fn_GetValues(int intVal1, int intVal2)
   {
     return  intVal1 * intVal2;
   }
   Static void Main(String[] args)
   {
      Delegate_Test objDel  = new Delegate_Test();
      Console.Writeline(" Please enter a value");
      int intVal1 = Int32.Parse(Console.ReadLine());
      int intVal2 =   Int32.Parse(Console.ReadLine());
      double Objres = objDel(intVal1, intVal2);
      Console.WriteLine("The Final Result is" + Objres);
      Console.Readline();
   }


Events:
An event in the .NET Framework world enables objects of a class to notify other objects that an action has been performed and that they should react. 

The model on which the events in the .Net Framework are based is the publisher-subscriber model.

The class that sends (or raises) the event is called the publisher

The classes that receive (or handle) the event are called subscribers.

In C#,VB any object can publish a set of events. Other applications can subscribe to these events.
When the publishing, class raises an event, all the subscribed applications are notified. But the publisher doesn’t know who is going to subscribe the event.  Delegates act as an intermediary between the publisher and the subscriber.

Example:
1) Create an ASP.Net web application with C#
2) We will create  a class that will publish the events. Add a new item to the project, a class file and call it Publisher.cs.
3) Add the code below inside the public class Publisher

  Public event DelegateEvent theevent;
  public delegate void
DelegateEvent(object from, EventArgs args);

  public void raiseEvent(EventArgs args)
  {
      
theevent(this, args);
  }

   public Publisher()
   {
   }

public void SendTheEvent()
   {
         MessageBox.Show(“the event is fired here”);
         this.raiseEvent(new EventArgs());
   }

Explanation :

First I declare the event

public event   DelegateEvent  theevent;

Use a delegate  to publish our event

public delegate void  DelegateEvent(object from, EventArgs args);

 We raise the event from the Publisher class

public void raiseEvent(EventArgs args)
{
theevent(this, args);
}

We trigger the event here 

 public void SendTheEvent()
    {
        MessageBox.Show(“the event is fired here”);
        this.raiseEvent(new EventArgs());
    }

Do not forget to add a reference to your project to the System.Windows.Forms namespace. At the beginning of the Publisher.cs file add this bit of code, using System.Windows.Forms.
4) Add another class file to the project and call it Subscriber.cs. Add the code below in the class Subscriber

Public Subscriber ()
 {

Publisher myclass = new Publisher ();
   
myclass.theevent += new Publisher.DelegateEvent(handletheevent);

myclass.SendTheEvent();

}

Let me explain what I do here
We create an instance of the Publisher class

Publisher myclass = new Publisher ();

We want to subscribe to this event delegate (DelegateEvent) of Publisher. So if the Publisher
raises any event, our method called the “handletheevent” is notified

myclass.theevent += new Publisher.DelegateEvent(handletheevent);

The event is fired here

myclass.SendTheEvent();

our event handler code goes here that responds to the event being fired

   private void handletheevent(object sender, EventArgs e)
   {
  
       MessageBox.Show(“Event handled in handletheevent of the Subscriber”);
       
       MessageBox.Show(“Who is the Sender?” + sender.GetType());
   }

Do not forget to add a reference to your project to the System.Windows.Forms namespace. At the beginning of the Subscriber.cs file add this bit of code, using System.Windows.Forms.
Events have the following properties:
  • The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
  • An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
  • Events that have no subscribers are never raised.
  • Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
  • When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously

Events and Delegates

Events in C# are implemented with delegates.
The publishing class defines a delegate. The subscribing class does two things: first, it creates a method that matches the signature of the delegate, and then it creates an instance of that delegate type encapsulating that method. When the event is raised, the subscribing class's methods are invoked through the delegate.
A method that handles an event is called an event handler. You can declare your event handlers as you would any other delegate.
Event handlers in the .NET Framework always return void and take two parameters.
 The first parameter is the "source" of the event (that is, the publishing object).
 The second parameter is an object derived from EventArgs. Your event handlers will need to follow this design pattern.
How to: Subscribe to and Unsubscribe from Events (C# Programming Guide)

To subscribe to events by using the Visual Studio IDE

  •  If you cannot see the Properties window, in Design view, right-click the form or control for which you want to create an event handler, and select Properties.
  •  On top of the Properties window, click the Events icon.
  •  Double-click the event that you want to create, for example the Load event.
Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view. For example, the following lines of code declare an event handler method that will be called when the Form class raises the Load event.
Private void Form1_Load(object sender, System.EventArgs e)
{
// Add your form load event handling code here.
}
The line of code that is required to subscribe to the event is also automatically generated in the InitializeComponent method in the Form1.Designer.cs file in your project. It resembles this:
this.Load += new System.EventHandler (this.Form1_Load);

To subscribe to events programmatically

1.     Define an event handler method whose signature matches the delegate signature for the event. For example, if the event is based on the EventHandler delegate type, the following code represents the method stub:
Void HandleCustomEvent (object sender, CustomEventArgs a)
{
         // Do something useful here.
}
2.     Use the addition assignment operator (+=) to attach your event handler to the event. In the following example, assume that an object named publisher has an event named RaiseCustomEvent. Note that the subscriber class needs a reference to the publisher class in order to subscribe to its events.
publisher.RaiseCustomEvent += HandleCustomEvent
Note that the previous syntax is new in C# 2.0. It is exactly equivalent to the C# 1.0 syntax in which the encapsulating delegate must be explicitly created by using the new keyword:
publisher.RaiseCustomEvent += new CustomEventHandler (HandleCustomEvent);
An event handler can also be added by using a lambda expression:
Public Form1()
{
InitializeComponent ();
// Use a lambda expression to define an event handler.
this.Click += (s,e) => { MessageBox.Show(
((MouseEventArgs)e).Location.ToString());};
}

To subscribe to events by using an anonymous method

·       If you will not have to unsubscribe to an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event. In the following example, assume that an object named publisher has an event named RaiseCustomEvent and that a CustomEventArgs class has also been defined to carry some kind of specialized event information. Note that the subscriber class needs a reference to publisher in order to subscribe to its events.
publisher.RaiseCustomEvent += delegate (object o, CustomEventArgs e)
{
String s = o.ToString () + " " + e.ToString ();
Console.WriteLine(s);
}
It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event. In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code

To prevent your event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, garbage collection will not delete your subscriber object.

To unsubscribe from an event

       Use the subtraction assignment operator (-=) to unsubscribe from an event:
publisher.RaiseCustomEvent -= HandleCustomEvent;
When all subscribers have unsubscribed from an event, the event instance in the publisher class is set to null.
 

No comments :

Post a Comment