主题:有关事件处理的问题
设计一个程序,使用Timer类的Elapsed事件,每1秒产生一个Elapsed事件,在事件处理方法里判断目前时间的秒数,若为偶数则显示“E”,若为奇数则显示“.”。在主方法Main()里判断目前的时间秒数,若为0则激活Elapsed事件,若为30则停止Elapsed事件。如此每隔30秒激活一次,每隔30秒停止一次。
下面是我写的部分程序,只是不知道主方法Main()该怎么样实现,望大家多多指点。
using System;
using System.Timers;
public class MsgSender
{
public delegate void MsgArrivedHandler(string msg);
public event MsgArrivedHandler msgArrivedEvent;
private Timer timer;
private int count;
public MsgSender()
{
count=0;
timer=new Timer(1000);
ElapsedEventHandler eeh=new ElapsedEventHandler(checkMsg);
timer.Elapsed+=eeh;
}
public void start() { timer.Start(); }
public void stop() { timer.Stop(); }
private void checkMsg(object source, ElapsedEventArgs e)
{
if(count%2==0)
{
msgArrivedEvent("E");
}
else
msgArrivedEvent(".");
count++;
}
}
public class MsgReceiver
{
public MsgReceiver(MsgSender msgSender)
{
MsgSender.MsgArrivedHandler msh=new MsgSender.MsgArrivedHandler(msgText);
msgSender.msgArrivedEvent+=msh;
}
private void msgText(string msg)
{
Console.Write("{0}", msg);
}
}
class MsgTest
{
static void Main()
{
//主要是不知道这个函数的写法。
}
}
下面是我写的部分程序,只是不知道主方法Main()该怎么样实现,望大家多多指点。
using System;
using System.Timers;
public class MsgSender
{
public delegate void MsgArrivedHandler(string msg);
public event MsgArrivedHandler msgArrivedEvent;
private Timer timer;
private int count;
public MsgSender()
{
count=0;
timer=new Timer(1000);
ElapsedEventHandler eeh=new ElapsedEventHandler(checkMsg);
timer.Elapsed+=eeh;
}
public void start() { timer.Start(); }
public void stop() { timer.Stop(); }
private void checkMsg(object source, ElapsedEventArgs e)
{
if(count%2==0)
{
msgArrivedEvent("E");
}
else
msgArrivedEvent(".");
count++;
}
}
public class MsgReceiver
{
public MsgReceiver(MsgSender msgSender)
{
MsgSender.MsgArrivedHandler msh=new MsgSender.MsgArrivedHandler(msgText);
msgSender.msgArrivedEvent+=msh;
}
private void msgText(string msg)
{
Console.Write("{0}", msg);
}
}
class MsgTest
{
static void Main()
{
//主要是不知道这个函数的写法。
}
}