我正在学习 Daniel M. Solis 的 Book Illustrated C# 2010 中的 C# 事件,并且正在尝试给出的关于 VS 2010 中事件的示例。出于某种原因,我收到了两次事件消息,但对于我的一生来说,我可以'不知道为什么。这是代码:
using System;
using System.Text;
using System.Threading;
namespace ConsoleApplication3
{
internal class MyTimerClass
{
public event EventHandler<MyTCEventArgs> Elapsed;
public void OnOneSecond(object source, EventArgs args)
{
if (Elapsed != null)
{
MyTCEventArgs mtcea = new MyTCEventArgs("Message from OnOneSecond");
Elapsed(source, mtcea);
}
}
//-----------------
private System.Timers.Timer MyPrivateTimer;
public MyTimerClass()
{
MyPrivateTimer = new System.Timers.Timer();
MyPrivateTimer.Elapsed += OnOneSecond;
MyPrivateTimer.Interval = 1000;
MyPrivateTimer.Enabled = true;
}
}
internal class ClassA
{
public void TimerHandlerA(object source, MyTCEventArgs args)
{
Console.WriteLine("Class A Message: {0}", args.Message);
}
}
internal class ClassB
{
public static void TimerHandlerB(object source, MyTCEventArgs args)
{
Console.WriteLine("Class B Message: {0}", args.Message);
}
}
internal class MyTCEventArgs : EventArgs
{
public string Message;
public MyTCEventArgs(string s)
{
Message = s;
}
}
internal class Program
{
private static void Main(string[] args)
{
ClassA ca = new ClassA();
MyTimerClass mc = new MyTimerClass();
mc.Elapsed += new EventHandler<MyTCEventArgs>(ca.TimerHandlerA);
mc.Elapsed += new EventHandler<MyTCEventArgs>(ClassB.TimerHandlerB);
Thread.Sleep(2250);
}
}
}
结果是以下消息: A 类消息:来自 OnOneSecond 的消息 B 类消息:来自 OnOneSecond A 类的消息 消息:来自 OnOneSecond 的消息 B 类消息:来自 OnOneSecond 的消息
为什么会发生两次?另外,当我删除 Thread.Sleep 行时,什么也没有发生。这也让我感到困惑。