Sunday, March 4, 2012

Events in C#

An event allows an object to broadcast a notification that may be of value to other objects listening to this event.

Consider you have a class (caller) monitoring stock market changes (callee). This class calls a method within another class which subscribes to an external service to periodically receive price updates.

One way to implement this would be to have a timer in the caller class which periodically fires, calling the method in the callee class, which then returns the stock prices.

A more elegant solution would be to have the callee fire an event when price changes and caller class to listen to those events. As soon as callee fires an event, caller will get notification and update the stock prices.

Events are useful for one class to broadcast a notification and all client objects listening to these events can do something with it. Events are created and used by using delegates. Review my previous post about delegates to get a better understanding about delegates and their purpose. Delegates are basically wrappers around a method allowing these methods to be called via delegates.

Let's use the above example to see how you can hook up events to get the stock price changes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    //create a delegate
    public delegate void ChangeStockPrice(object sender, EventArgs e);
    
    public class GetStockPrices
    {
         public string _ticker;
         public double _price;

         
         //create an event
         public event ChangeStockPrice PriceUpdated;

        //when ever price changes, raise the PriceUpdated event;
        protected virtual void OnPriceChange(EventArgs e)
           {
                  if (PriceUpdated !=null)
                  PriceUpdated(this, e);
           }

       //create a method to change stock price
        public void ChangePrice(string ticker,double price)
           {
                _ticker=ticker;
                _price = price;
                // fire the event
                OnPriceChange(EventArgs.Empty);
            }
       }
    //create an event listener class
    public class EventListener
   {
     private GetStockPrices stockprice;
     //attach event
    public void Attach(GetStockPrices stock)
     {
         stockprice=stock;
         stockprice.PriceUpdated += new ChangeStockPrice(PriceChanged);
     }
     protected void PriceChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Ticker: {0}, Price: {1}", stockprice._ticker, stockprice._price);
    }
    //you can detach an event
    public void Detatch()
    {
        stockprice.PriceUpdated -= new ChangeStockPrice(PriceChanged);
    }
   }

}

Now let's call the above class which will fire an event showing up the stock price information.

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
                   
        static void Main(string[] args)
        {
            
           GetStockPrices stockprice= new GetStockPrices();
            EventListener Listener = new EventListener();
            Listener.Attach( stockprice );
            stockprice.ChangePrice("MSFT",33.50);
            //detatch
            Listener.Detatch();
            Console.Read();
      }
    }
}


Events allow multiple subscribers to subscribe to an event fired by one class, instead of trying to poll the class to see if something change. When you are running multi-threaded applications, the parent thread can fire off another thread and then listen to the object on child thread raising the event once the processing is complete.

Hope this helps in understanding events and how you can use them in your application.

Thank you.

No comments:

Post a Comment