timer tick in form is re-entrant ??

L

Liam

Hi
Anyone else encountered this problem?

In a VB or C# project I have 2 forms. Both have a forms timer. The
timer in the one of the forms is running at 55ms and raises an event
which is handled by the first form. The handler disables, sets the
interval, then re-enables the timer on its form. It also sleeps for 60
ms.

The problem I've found occurs when the 55ms time overruns (say when
the computer is doing something else ). After the timer has been
re-enabled the first timer tick ( the one raising the event ) is
called again even though the first instance is still running. Hence
the call stack looks like this

Tick1()
RaiseEvent
...
Re-enable timer
Tick()

The key here is the re-enabling of the first timer. If that is not
done then the problem does not occur.

Anyone else encountered this? It can't be considered normal behaviour
for the timer tick can it?

thanks for any input
Liam

More detailed code follows

Public Class DialogForm
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Event DialogEvent()

Private Sub DialogForm_Closing(ByVal sender As Object, ByVal e As
System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Timer1.Enabled = False
End Sub

Dim b As Boolean = False
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
If b = True Then
ErrorLabel.Text = Str(Val(ErrorLabel.Text) + 1)
End If
b = True

RaiseEvent DialogEvent()

b = False
End Sub

End Class

Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Private Sub DialogButton_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles DialogButton.Click
Dim f As New DialogForm
AddHandler f.DialogEvent, AddressOf DialogEventHandler
'f.ShowDialog()
f.Show()
End Sub

Sub DialogEventHandler()
Sleep(50)

Timer1.Enabled = False
Timer1.Interval = 1000
Timer1.Enabled = True
End Sub
End Class
 
T

Tian Min Huang

Hello Liam,

Thanks for your post. I reproduced the problem you are facing and found
that the problem may be caused by the following line:

Sub DialogEventHandler()
......
Timer1.Enabled = True
End Sub

If I comment out Timer1.Enabled, now that it works properly. To work around
the problem, I suggest you not to set Timer1.Enabled in the event handler.
Or you can disable DialogForm.Timer1 (.Enabled = False) before raise the
event, and enable it (DialogForm.Timer1.Enabled=True) afterwards.

Hope this helps.

Regards,

HuangTM
Microsoft Online Partner Support
MCSE/MCSD

Get Secure! -- www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top