My goal is to wrap the multimedia functions into a class that operates similar to the timer control. I need something with a high accuracy and precision. It works but I dont think Im managing the threads right. Heres what I do:
So to summarize I start a thread that checks the time variables. Once the correct condition has been reached the event is fired. This goes to a handler that in turn starts the timer calling the StartTimer() member. This is the point where I think im going wrong. When I set CheckThread a second time, im blowing away from previous reference to the first thread? It should die on its own, but how do I know? If none of the threads die off, I could be infinitely creating new threads. Is there a better way to do this?
Visual Basic:
Imports System.Threading
Imports System.Threading.Thread
Public Class CTimer
Private Declare Function timeGetTime Lib "winmm.dll" () As Integer
Private Declare Function timeBeginPeriod Lib "winmm.dll" (ByVal uPeriod As Integer) As Integer
Private Declare Function timeEndPeriod Lib "winmm.dll" (ByVal uPeriod As Integer) As Integer
Public Event TimerElapsed()
Private CheckThread As Thread
Private objLock As Object
Private intInterval As Integer = 0
Private intStartTime As Integer = 0
Public Sub New()
timeBeginPeriod(1)
objLock = New Object
End Sub
Public Sub StartTimer(ByVal interval As Integer)
intInterval = interval
intStartTime = timeGetTime()
CheckThread = New Thread(AddressOf Me.CheckTime)
Thread.CurrentThread.Priority = ThreadPriority.Highest
CheckThread.Start()
End Sub
Public Sub StopTimer()
If Not CheckThread Is Nothing Then
Try
CheckThread.Abort() 'Causing a problem
CheckThread = Nothing
Catch ex As Exception
MsgBox("CTimer Thread would not abort", MsgBoxStyle.Critical, "ERROR")
End Try
End If
timeEndPeriod(1)
End Sub
Private Sub CheckTime()
Dim start_time As Integer
Dim interval As Integer
SyncLock objLock
start_time = intStartTime
interval = intInterval
End SyncLock
While timeGetTime() - start_time < interval
Sleep(1)
End While
RaiseEvent TimerElapsed()
End Sub
End Class
So to summarize I start a thread that checks the time variables. Once the correct condition has been reached the event is fired. This goes to a handler that in turn starts the timer calling the StartTimer() member. This is the point where I think im going wrong. When I set CheckThread a second time, im blowing away from previous reference to the first thread? It should die on its own, but how do I know? If none of the threads die off, I could be infinitely creating new threads. Is there a better way to do this?