-1

So i want to check the current time every second and if seconds == 0 raise event and show current time:

using System.Timers;

public delegate void TimeHandler(object sender, TimeEventArgs e);

public class Clock
{
    private Timer timer;
    public event TimeHandler CurrentTime;

    public Clock()
    {
        timer = new Timer();
        timer.Elapsed += timer_Elapsed;
        timer.Interval = 1000;
    }

    public void Start()
    {
        timer.Enabled = true;
        timer.Start();
    }

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        DateTime time = DateTime.Now;
        int sec = time.Second;
        if (sec == 0)
            if (CurrentTime != null)
                CurrentTime(this, new TimeEventArgs(time));
    }
}

public class TimeEventArgs
{
    public readonly DateTime Time;

    public TimeEventArgs(DateTime time)
    {
        Time = time;
    }
}

Usage:

Clock clock = new Clock();
clock.CurrentTime += Clock_CurrentTime;
clock.Start();

private static void Clock_CurrentTime(object sender, TimeEventArgs e)
{
    Console.WriteLine(e.Time.ToShortTimeString());
}

But it seems like the timer elapsed not starting.

david hol
  • 1,272
  • 7
  • 22
  • 44

1 Answers1

0

Your timer_Elapsed mismatches currentTime and CurrentTime. If you check the delegate you should use the capitalized name of the handler.

You could make certain that the Elapsed handler is called by setting a breakpoint in it or put a log message directly there, right at the beginning.

Finally, Clock_CurrentTime will only be called once per minute.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51
  • Please see my edit, my console application still ends without get into this timer_elapsed method – david hol Oct 24 '16 at 06:47
  • Sure, if you don't keep the console app running: http://stackoverflow.com/questions/11512821/how-to-stop-c-sharp-console-applications-from-closing-automatically?rq=1 -- Just let it wait for keypress: http://stackoverflow.com/questions/5891538/listen-for-key-press-in-net-console-app?rq=1 – JeffRSon Oct 24 '16 at 06:49