03Usr
03Usr

Reputation: 3435

Event handling, how to chain events

I have the following code, a Metronome class creates events at a tick of 3 seconds, and a Listener class hears the metronome ticks and prints "Ticked" to the console every time it receives an event. What I also want to do is chain further events meaning before or after the "Tick" I should be able process other events, the output I am looking on the console window is something like this:

"Processed initial event" "Ticked" "Processed the final event"

Is this possible?

namespace Events
{
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            var m = new Metronome();
            var l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }

    public class Metronome
    {
        public EventArgs e = null;
        public delegate void TickHandler(Metronome m, EventArgs e);
        public event TickHandler Tick;

        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    Tick(this, e);
                }
            }
        }
    }

    public class Listener
    {
        public void Subscribe(Metronome m)
        {
            m.Tick += new Metronome.TickHandler(HeardIt);
        }

        private void HeardIt(Metronome m, EventArgs e)
        {
            Console.WriteLine("Ticked");
        }
    }
}

Upvotes: 1

Views: 531

Answers (1)

Maarten
Maarten

Reputation: 22955

You can add eventhandlers yourself.

var m = new Metronome();
m.Tick += (s, e) => {
    Console.WriteLine("Processed initial event");
};
var l = new Listener();
l.Subscribe(m);
m.Tick += (s, e) => {
    Console.WriteLine("Processed the final event");
};
m.Start();

This should give you the wanted result. Keep in mind that to order in which you add the events is the order that they are executed in.

Or, if you want multiple listeners:

public class Listener {
    private string _msg;
    public Listener (string msg) {
        _msg = msg;
    }

    public void Subscribe(Metronome m) {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e) {
        Console.WriteLine(msg);
    }
}

var m = new Metronome();
new Listener("Processed initial event").Subscribe(m);
new Listener("Ticked").Subscribe(m);
new Listener("Processed the final event").Subscribe(m);
m.Start();

Upvotes: 1

Related Questions