事件处理,如何链接事件

时间:2014-04-02 10:25:13

标签: c# events event-handling

我有以下代码,Metronome类以3秒的刻度创建事件,并且Listener类听到节拍器刻度和打印" Ticked"每次收到活动时都到控制台。我还想做的是在" Tick"之前或之后链接其他事件。我应该能够处理其他事件,我在控制台窗口上看到的输出是这样的:

"已处理的初始事件" "打勾" "处理了最后的事件"

这可能吗?

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");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以自己添加事件处理程序。

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();

这应该给你想要的结果。请记住,添加事件的顺序是它们的执行顺序。

或者,如果你想要多个听众:

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();