下边Demo如果是在vs2012 下运行需要进入调试模式一遍才能正常运行出结果
namespace ConsoleApplication2 { public delegate void messageHandler(string msg); public class Connection { public event messageHandler MessageArried; private Timer pollTimer; public Connection() { pollTimer = new Timer(100); 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("Hello Mum!"); } } } class Display { public void DisplayMsg(string message) { Console.WriteLine("Msg arrived:{0}", message); } } class Program { static void Main(string[] args) { Connection conn = new Connection(); Display display = new Display(); conn.MessageArried += new messageHandler(display.DisplayMsg); conn.Connect(); Console.ReadKey(); } } }