I’m learning about C# events in the Book Illustrated C# 2010 by Daniel M. Solis and am trying out the example given about events in VS 2010. For some reason I get the event message twice, but for the life of me I can’t figure out why. Here is the code:
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);
}
}
}
The result is the following message:
Class A Message: Message from OnOneSecond
Class B Message: Message from OnOneSecond
Class A Message: Message from OnOneSecond
Class B Message: Message from OnOneSecond
Why does it happen twice? Also seperately from that, when I remove the Thread.Sleep line nothing happens at all. This confuses me also.
Your timer is running on another thread, so it is not blocked by the call to
Sleep(). It has an interval of1000and you sleep for2250. Thus, theTickevent will be raised twice in that period, which is what you are seeing.The reason that nothing happens at all if you remove the sleep is because your program exits before a
Tickevent is fired. Remember, that event is raised every1000ms and it takes much less time than that for the program to exit.