Wednesday, April 20, 2011

Why use Events?

I'm understanding how events work in C# (am a fair newbie in this field). What I'm trying to understand is why we use events.

Do you know a well coded / architected app which uses events?

** rest of message snipped and put in as an answer**

From stackoverflow
  • You could always build your own way of sending/receiving events, subscribing/unsubscribing to event sources. But the language gives you a simple/standard way of doing it, so that is a good reason to use language "events" instead of your own events technique.

    Also, using the language "events" allows you to do all kinds of cool things using reflection because it is standardized.

    As to why using an event technique at all. There are all kinds of real-life examples where this is quite usefull and simpler to use events. Events are almost similar in their usefullness than Windows Messages are.

  • At the most basic conceptual level, Events are what let the computer react to what you do, rather than you being required to react to what the computer does. When you're sitting in front of your PC with several applications running (including the operating system), and several clickable objects available in each context for you to choose among, Events are what happens when you choose one and all the pieces involved can be properly notified.

    Even moving your mouse around kicks off a stream of events (to move the cursor, for instance).

  • You can implement the Observer Pattern in C# with Events and Delegates.

    Here is a link to an article that describes such: http://blogs.msdn.com/bashmohandes/archive/2007/03/10/observer-pattern-in-c-events-delegates.aspx


    alt text

  • *this used to be in the question body

    What would be very useful is a non trivial example of an app which uses events (guess it really helps testing too?)

    Thoughts so far are:

    Why use Events or publish / subscribe?

    Any number of classes can be notified when an event is raised.

    The subscribing classes do not need to know how the Metronome (see code below) works, and the Metronome does not need to know what they are going to do in response to the event

    The publisher and the subscribers are decoupled by the delegate. This is highly desirable as it makes for more flexible and robust code. The metronome can change how it detects time without breaking any of the subscribing classes. The subscribing classes can change how they respond to time changes without breaking the metronome. The two classes spin independently of one another, which makes for code that is easier to maintain.

    class Program
    {
        static void Main()
        {
         // setup the metronome and make sure the EventHandler delegate is ready
         Metronome metronome = new Metronome();
    
         // wires up the metronome_Tick method to the EventHandler delegate
         Listener listener = new Listener(metronome);
         ListenerB listenerB = new ListenerB(metronome);
         metronome.Go();
        }
    }
    
    public class Metronome
    {
        // a delegate
        // so every time Tick is called, the runtime calls another method
        // in this case Listener.metronome_Tick and ListenerB.metronome_Tick
        public event EventHandler Tick;
    
        // virtual so can override default behaviour in inherited classes easily
        protected virtual void OnTick(EventArgs e)
        {
         // null guard so if there are no listeners attached it wont throw an exception
         if (Tick != null)
          Tick(this, e);
        }
    
        public void Go()
        {
         while (true)
         {
          Thread.Sleep(2000);
          // because using EventHandler delegate, need to include the sending object and eventargs 
          // although we are not using them
          OnTick(EventArgs.Empty);
         }
        }
    }
    
    
    public class Listener
    {
        public Listener(Metronome metronome)
        {
         metronome.Tick += new EventHandler(metronome_Tick);
        }
    
        private void metronome_Tick(object sender, EventArgs e)
        {
         Console.WriteLine("Heard it");
        }
    }
    
    public class ListenerB
    {
        public ListenerB(Metronome metronome)
        {
         metronome.Tick += new EventHandler(metronome_Tick);
        }
    
        private void metronome_Tick(object sender, EventArgs e)
        {
         Console.WriteLine("ListenerB: Heard it");
        }
    }
    

    Full article I'm writing on my site: http://www.programgood.net/

    nb some of this text is from http://www.akadia.com/services/dotnet_delegates_and_events.html

    Cheers.

  • To provide a concrete normal world example....

    You have a form, the form has a listbox. There's a nice happy class for the listbox. When the user selects something from the listbox, you want to know, and modify other things on the form.

    Without events:

    You derive from the listbox, overriding things to make sure that your parent is the form you expect to be on. You override a ListSelected method or something, that manipulates other things on your parent form.

    With events: Your form listens for the event to indicate a user selected something, and manipulates other things on the form.

    The difference being that in the without events case you've created a single-purpose class, and also one that is tightly bound to the environment it expects to be in. In the with events case, the code that manipulates your form is localized into your form, and the listbox is just, well, a listbox.

0 comments:

Post a Comment