Reputation: 2696
I'm learning events and delegates and decided to write such console application. Program should message me every 3 and 5 seconds. But it doesn't do anything.
I have a class WorkingTimer
:
class WorkingTimer
{
private Timer _timer = new Timer();
private long _working_seconds = 0;
public delegate void MyDelegate();
public event MyDelegate Every3Seconds;
public event MyDelegate Every5Seconds;
public WorkingTimer()
{
_timer.Interval = 1000;
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_working_seconds++;
if (Every3Seconds != null && _working_seconds % 3 == 0)
Every3Seconds();
if (Every5Seconds != null && _working_seconds % 5 == 0)
Every5Seconds();
}
}
and actually the program:
class Program
{
static void Main(string[] args)
{
WorkingTimer wt = new WorkingTimer();
wt.Every3Seconds += wt_Every3Seconds;
wt.Every5Seconds += wt_Every5Seconds;
}
static void wt_Every3Seconds()
{
Console.WriteLine("3 seconds elapsed");
}
static void wt_Every5Seconds()
{
Console.WriteLine("5 seconds elapsed");
}
}
So, when I run it doesn't do anything. But I tried to make exactly same program in Windows Form Application and it worked great. The difference only is in Timer events Elapsed and Tick.
What am i doing wrong?
Upvotes: 1
Views: 86
Reputation: 6246
The program exits at the end of the Main
function. Try adding a dummy Console.ReadLine()
to keep it running.
The resulting code would be:
static void Main(string[] args)
{
WorkingTimer wt = new WorkingTimer();
wt.Every3Seconds += wt_Every3Seconds;
wt.Every5Seconds += wt_Every5Seconds;
Console.ReadLine();
}
Upvotes: 3