Threading.Timer won't dispose

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

Guest

Hello,
I have used a thread timer as in the documentation on MSDN in my VB.NET
application.

Using System.Threading.Interlocked.Increment I increment the counter to a
certain point, perform an operation, then dispose of the TimerReference. In
this case, the operation is simply enabling a checkbox control.

I have found that the timer will continue to tick at least twice after it is
disposed. Sometimes it will tick several HUNDRED times after it has been
disposed. I could handle this with an empty Catch but that's sloppy.

I tried using System.GC.Collect on the last tick, but no change.
I can't use a forms.timer because this method is sometimes called from a
remote client app.

Any ideas?

Here is a sample of the code:

Private Sub chkTimeTemp_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles chkTimeTemp.CheckedChanged

'do stuff here

'use thread timer
Dim tmrDelegate As New Threading.TimerCallback(AddressOf TTTX)
Dim TTTxStateObj As New TTStateObjClass
'initialize the counter
TTTxStateObj.Counter = 0
'get the duration of the transition in tenths of a second
If chkTimeTemp.Checked Then
TTTxStateObj.TimeOut = glbTTTxOnSpeed / 100
Else
TTTxStateObj.TimeOut = glbTTTxOffSpeed / 100
End If
Console.WriteLine("timeout = " & TTTxStateObj.TimeOut.ToString)
Dim tmrTTTx As New System.Threading.Timer _
(tmrDelegate, TTTxStateObj, 0, 100)
End Sub
Private Sub TTTX(ByVal stateobj As Object)
Try
Dim ttTick As TTStateObjClass = CType(stateobj, TTStateObjClass)
If Not ttTick.TimerRerence Is Nothing Then
System.Threading.Interlocked.Increment(ttTick.Counter)
Console.WriteLine(ttTick.Counter & " out of " &
ttTick.TimeOut.ToString)
If ttTick.Counter >= ttTick.TimeOut Then
'kill the timer
ttTick.TimerRerence.Dispose()
'enable the chk
chkTimeTemp.Enabled = True
System.GC.Collect()
End If
End If

Catch ex As Exception
Console.WriteLine(ex.Message)
chkTimeTemp.Enabled = True
End Try
End Sub
 

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

Back
Top