1

I am new to threading and do not know anything about how it should be used. I am having trouble with my clock. My clock does not give me correct local time, instead gives me about 10-15 minutes delayed time.

I think there is something wrong or missing with my code:

private void MainWindow_Load(object sender, EventArgs e)
{
  new System.Threading.Timer((state) => 
  { 
    if (!label2.IsHandleCreated) 
      return; 
    BeginInvoke((Action)delegate() 
      { label2.Text = "    " + DateTime.Now.ToString("hh:MM:ss") + "  " +
                               DateTime.Now.ToShortDateString(); });
      }, null, 1000, 1000);
  }

I have read that begininvoke should always be paired with endinvoke. But how do I do it?

Edit: I need to know why this code give me delayed time like now its 12:23 here but the program shows 12:03, it always starts at 12:03 when I re-run it. Also sometimes the clock stops. Why?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Brian Sanchez
  • 149
  • 2
  • 16
  • 1
    You do not begininvoke - you invoke. WIthout begin. – TomTom Mar 06 '14 at 16:11
  • 2
    Also, you should keep at least one strong reference to the timer, otherwise it's gonna be eligible for garbage collection and be collected at any time. – dcastro Mar 06 '14 at 16:13
  • possible duplicate of [How do I create a timer in WPF?](http://stackoverflow.com/questions/11559999/how-do-i-create-a-timer-in-wpf) – EkoostikMartin Mar 06 '14 at 16:15
  • 1
    And maybe you should learn basic programming concepts before jumping into WPF. – Bauss Mar 06 '14 at 16:15
  • 1
    @TomTom, @Brian Sanchez: FYI, [`BeginInvoke` without `EndInvoke`](http://stackoverflow.com/a/532732/2101267) on a `Control` is fine. `Invoke` would be fine as well, but will tie up the thread unnecessarily. – Dark Falcon Mar 06 '14 at 16:16
  • 1
    @TomTom Why? How is blocking this tick handler until the UI finishes updating preferable to letting it finish handling the event and continue on with its business? It's not like you need to do something after the UI has been updated. – Servy Mar 06 '14 at 16:18
  • Since you are using WPF why not use a Dispatch timer? – Tsukasa Mar 06 '14 at 16:23
  • Thanks for your answers, I need to know why this code give me delayed time like now its 12:23 here but the program shows 12:03. Also sometimes the clock stops. Why? – Brian Sanchez Mar 06 '14 at 16:24
  • I don't believe this is WPF Load is WinForms. WPF event is Loaded – Tsukasa Mar 06 '14 at 16:26
  • **I have edited your question tags.** you're not using WPF, you're using winforms. – Federico Berasategui Mar 06 '14 at 16:28
  • @HighCore Oh sorry, its winforms right. thanks for correcting – Brian Sanchez Mar 06 '14 at 16:29

1 Answers1

1

Your format string hh:MM:ss is showing you hours (12 hour clock) : month : seconds. You probably intended hh:mm:ss See Custom Date and Time Format Strings on MSDN for a detailed description.

Sarin
  • 1,255
  • 11
  • 14