您的位置:首页 > 编程语言 > C#

C#中使用事件(代码示例)

2008-01-24 10:40 561 查看
/**********************************************************************************************
* Date:2008-01-24
* Function:Exercise for using event in .Net
* Author:Carlo Zhai
* Note:
* C#中使用事件需要的步骤
1.创建一个委托
2.将创建的委托与特定事件关联
3.编写事件处理程序
4.利用编写的事件处理程序生成一个委托实例
5.把这个委托实例添加到产生事件对象的事件列表中去,这个过程又叫订阅事件
* *********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;

namespace EventUsing_SimpleDemo
{
public delegate void MessageHandler(string messageTxt);//1.创建一个委托 这里必须是多播委托(void)
public class Connection
{
private delegate void InternalEventHandler(string messageTxt);
private event InternalEventHandler InternalEventArrived;
public event MessageHandler MessageArrived;//2.将创建的委托与特定事件关联,public private 等修饰符都可以使用
private Timer pollTimer;
public Connection()
{
pollTimer = new Timer(100);//100milliseconds
pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);
InternalEventArrived += new InternalEventHandler(Connection_InternalEventArrived);
}

public void Connect()
{
pollTimer.Start();
}
public void DisConnect()
{
pollTimer.Stop();
}
void CheckForMessage(object sender, ElapsedEventArgs e)
{
Random random = new Random();
if ((random.Next(0, 9) == 5) && (MessageArrived != null))//MessageArrived!=null这个非常重要,容易遗忘
{
MessageArrived(string.Format("Hello,the time is {0}", DateTime.Now.ToString()));//触发事件
}
if ((random.Next(0, 9) == 8) && (InternalEventArrived != null))//MessageArrived!=null这个非常重要,容易遗忘
{
InternalEventArrived(string.Format("The Internal Event Arrived at {0}", DateTime.Now.ToString()));//触发事件
}
}
void Connection_InternalEventArrived(string messageTxt)
{
Console.WriteLine(messageTxt);
}
}

class Program
{
[STAThread]
static void Main(string[] args)
{
Connection myConnection = new Connection();
//下面这两句注释掉再对比
myConnection.MessageArrived += new MessageHandler(Display.DisplayMsg);//5.把这个委托实例添加到产生事件对象的事件列表中去,这个过程又叫订阅事件
myConnection.MessageArrived += new MessageHandler(myConnection_MessageArrived);
myConnection.Connect();
Console.WriteLine("Please input - to remove the event handle myConnection_MessageArrived;/n input + to add the event handle myConnection_MessageArrived;/n input Enter to quit;");
while (true)
{
string inStr = Console.ReadLine();
if (inStr.Equals("-"))
myConnection.MessageArrived -= myConnection_MessageArrived;
if (inStr.Equals("+"))
myConnection.MessageArrived += new MessageHandler(myConnection_MessageArrived);
if (inStr == "")
return;
}

}

static void myConnection_MessageArrived(string messageTxt)
{
Console.WriteLine("The method or operation is not implemented.");
}

}

public class Display
{
//编写事件处理程序
public static void DisplayMsg(string displayMsg)
{
Console.WriteLine(string.Format("MessageArrived{0}", displayMsg));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐