[ACCEPTED]-Why use Events?-architecture

Accepted answer
Score: 17

To provide a concrete normal world example....

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

Without events:

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

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

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

Score: 12

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

Thoughts so 18 far are:

Why use Events or publish / subscribe?

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

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

The publisher 12 and the subscribers are decoupled by the 11 delegate. This is highly desirable as it 10 makes for more flexible and robust code. The 9 metronome can change how it detects time 8 without breaking any of the subscribing 7 classes. The subscribing classes can change 6 how they respond to time changes without 5 breaking the metronome. The two classes 4 spin independently of one another, which 3 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 2 article I'm writing on my site: http://www.programgood.net/

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

Cheers.

Score: 7

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

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

enter image description here

Score: 1

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

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

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

Score: 1

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

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

Score: 0

If you are confused on why use events when 12 we can achieve the same functionality with 11 delegates, then the answer is :

  1. the client 10 (the class where subscription occurs) cannot 9 directly call the invoke method on the delegate 8 when using events

    instanceOfClassWithDelegate.sampleDelegate.Invoke(); // not 7 possible with events

  2. the client cannot list 6 or clear the functions assigned to the delegate 5 when using events

    instanceOfClassWithDelegate.sampleDelegate 4 = null; // not possible when using events

  3. events 3 are a better way to encapsulate logic as 2 is implicitly understood

The entire credit 1 to this answer goes to this blog : https://dev.to/willydavidjr/why-use-events-instead-of-delegates-in-c-40k8

More Related questions