Multi thread stops when opening a new form

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Below is the code with the problem (it is just one form):
When you run the code, you hear a beep every second, the beep is on a new
thread.
When you push the button 100 forms are opend, the beep should continue, but
is doesn't.
Sometimes it already stops when you open 1 form, but to make sure the sample
works it will open 100 forms.
Who can help me?

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Me.ClientSize = New System.Drawing.Size(292, 266)
Dim Button1 As New System.Windows.Forms.Button
Button1.Text = "Open forms"
AddHandler Button1.Click, AddressOf Button1_Click
Me.Controls.Add(Button1)
RunTimer()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Dim i As Integer
For i = 1 To 100
Dim NewForm As New Form
NewForm.Size = New System.Drawing.Size(152, 62)
NewForm.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen
NewForm.Text = i
NewForm.Show()
Next
End Sub
Sub RunTimer()
Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask)
Dim TimerItem As New System.Threading.Timer(TimerDelegate, Nothing,
0, 1000)
End Sub
Sub TimerTask(ByVal StateObj As Object)
Beep()
End Sub
 
jt said:
Below is the code with the problem (it is just one form):
When you run the code, you hear a beep every second, the beep is on
a new thread.
When you push the button 100 forms are opend, the beep should
continue, but is doesn't.
Sometimes it already stops when you open 1 form, but to make sure
the sample works it will open 100 forms.
Who can help me?



Read the "Hints" section in the documentation on the Timer class: The GC
eats all of them. => declare them as a field in the class.



Armin
 
Armin, thanks, that was what i was looking for, i had no idea the Garbage
Collection was the problem.
Here is the new code that works (in case someone needs it):

Dim TimerDelegate As New Threading.TimerCallback(AddressOf TimerTask)
Dim TimerItem As New System.Threading.Timer(TimerDelegate, TimerItem, 0,
1000)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Me.ClientSize = New System.Drawing.Size(292, 266)
Dim Button1 As New System.Windows.Forms.Button
Button1.Text = "Open forms"
AddHandler Button1.Click, AddressOf Button1_Click
Me.Controls.Add(Button1)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Dim i As Integer
For i = 1 To 100
Dim NewForm As New Form
NewForm.Size = New System.Drawing.Size(152, 62)
NewForm.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen
NewForm.Text = i
NewForm.Show()
Next
End Sub
Sub TimerTask(ByVal StateObj As Object)
Beep()
End Sub
End Class
 
Back
Top