1

I'm getting a weird malfunction when using the DateTime.AddSeconds command in a loop. Label1 is supposed to show "NewDT" before the loop starts, but for some reason it doesn't. Funny thing is when add a Messagebox right over the loop, the label shows what I want it too.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim Dt As DateTime = Now() 'It shows current datetime
    Dim NewDT As DateTime = Now()
    NewDT = NewDT.AddSeconds(10) 'It adds 10 seconds too the current datetime.
    Label1.Text = NewDT

    Do While NewDT.Second > DateTime.Now.Second 'Loops until system time matches NewDT

    Loop
    MsgBox("done")
End Sub
The Blue Dog
  • 2,475
  • 3
  • 19
  • 25
Paul Etscheit
  • 493
  • 1
  • 6
  • 16
  • Code work properly for me without msgbox. try this `Label1.Text = NewDT.ToString` –  Aug 31 '14 at 14:54
  • a) your loop is comparing Seconds, not time; b) there is nothing inside your loop. If you *were* changing the label, the loop would have to complete before the form updates. Use `label1.Refresh` to force it to update. – Ňɏssa Pøngjǣrdenlarp Aug 31 '14 at 14:58
  • Got it working. Thanks. Well I'm just using the loop to make the program wait until the time is matched. I know it's not ideal. Is there any better solution? – Paul Etscheit Aug 31 '14 at 15:01
  • 1
    `NewDT` starts out Now+10 secs and would never execute if you were actually comparing time. – Ňɏssa Pøngjǣrdenlarp Aug 31 '14 at 15:04

2 Answers2

2

There are no malfunction.

The WM_PAINT message is queued but only processed after you've "left" the function.

The reason as to why it works when you show a modal message box (MsgBox) is because the dialog calls Application.DoEvents which enables the application to process queued messages.

Community
  • 1
  • 1
Bjørn-Roger Kringsjå
  • 9,849
  • 6
  • 36
  • 64
1

The problem is that the text of the label will not be updated untill the end of the sub. After the Label1.Text = NewDT line, add Label1.Refresh(), and then NewDT will be presented before the loop starts.

If you want a more ideal solution, you can use the Sleep method.

Eminem
  • 870
  • 5
  • 20