using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers; // 计时器
namespace DemoConnection
{
public delegate void MessageHandler(string messageText);
public class Connection
{
public event MessageHandler MessageArrived; // 定义一个委托的实例
private Timer pollTimer;
public Connection()
{
pollTimer = new Timer(100);
pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage); // 每一百毫秒执行一次
}
public void Connect()
{
pollTimer.Start();
}
public void Disconnect()
{
pollTimer.Stop();
}
private static Random random = new Random();
private static int count = 0;
private void CheckForMessage(object source,ElapsedEventArgs e)
{
Console.WriteLine("检测新消息.");
if ((random.Next(9) == 0) && (MessageArrived != null))
{
count++;
//触发MessageArrived事件
MessageArrived("第"+count+"次问候您!");
}
}
}
public class Display
{
public void DisplayMessage(string message)
{
Console.WriteLine("消息来了:{0}",message);
}
}
class Program
{
static void Main(string[] args)
{
Connection myConnection = new Connection();
Display myDisplay = new Display();
//将一个委托实例赋值给事件MessageArrived
myConnection.MessageArrived += new MessageHandler(myDisplay.DisplayMessage);
myConnection.Connect();
Console.ReadKey();
}
}
}
方法论:说实话,我还不太理解这段代码。
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6803018.html,如需转载请自行联系原作者