下边Demo如果是在vs2012 下运行需要进入调试模式,并且用合理的速度调试一遍才能正常运行出结果。
namespace ConsoleApplication2 { public delegate void MessageHanlder(Connection source, MessageArrivedEventArgs e); public class Connection { public event MessageHanlder MessageArried; private Timer pollTimer; public string name { get; set; } public Connection() { pollTimer = new Timer(700); pollTimer.Elapsed += new ElapsedEventHandler(CheckForMsg); } public void Connect() { pollTimer.Start(); } public void DisConnect() { pollTimer.Stop(); } private static Random random = new Random(); void CheckForMsg(object sources, ElapsedEventArgs e) { Console.WriteLine("Checking for new messages"); if ((random.Next(9) == 0) && (MessageArried != null))//使用了委托语法,但语法略有不同,其含义为“事件是否有订阅者?”如果没有订阅者,MessageArrived就是null,也就不会引发事件。 { MessageArried(this, new MessageArrivedEventArgs("Hello Mum!")); } } } class Display { public void DisplayMsg(Connection source, MessageArrivedEventArgs e) { Console.WriteLine("message arrived from:{0}", source.name); Console.WriteLine("message Text:{0}", e.Message); } } class Program { static void Main(string[] args) { Connection conn1 = new Connection(); conn1.name = "First conneciton"; Connection conn2 = new Connection(); conn2.name = "second connection"; Display display = new Display(); conn1.MessageArried += new MessageHanlder(display.DisplayMsg);//注册事件 conn2.MessageArried += delegate(Connection source, MessageArrivedEventArgs e)//匿名方式注册事件 { Console.WriteLine("dddddddddd message arrived from:{0}", source.name); Console.WriteLine("dddddddddd message Text:{0}", e.Message); }; conn2.Connect(); conn1.Connect(); Console.ReadKey(); } } public class MessageArrivedEventArgs : EventArgs { private string message; public string Message { get { return message; } } public MessageArrivedEventArgs() { message = "No message sent"; } public MessageArrivedEventArgs(string newmsge) { message = newmsge; } } }