[RESOLVED] Timer multi-threading help
hi everyone. can anyone help me with using the timer component to run another thread. when my program is running, i want to run a seperate thread in the background, to run a function that will check a device connected to a usb drive.
the problem is, when the timer calls the function, my whole program freezes up until the timer finishes (this timer has to run through out the life span of the program)
any suggestions?
im using visual studio 2008 express edition (visual basic). i add the timer component (enabled= true, interval=2000 (every 2 seconds). when the timer event firest, i call a function.
Re: Timer multi-threading help
Check out BackgroundWorker on MSDN. It has a lot of good examples and is very simple to use.
Re: Timer multi-threading help
Assuming that you only want one instance of this task executing at a time, add a BackgroundWorker and call its RunWorkerAsync method in the Timer's Tick event handler. See my signature for an example. Note that if there's any chance that the previous task won't have finished when the Timer Ticks then you must test the IsBusy property of the BGW.
If you do, or might, want multiple instances of the task running at the same time then you can either create Thread objects explicitly or else use the ThreadPool class.
vb.net Code:
Private Sub Timer1_Tick(ByVal sender As Object, _
ByVal e As EventArgs) Handles Timer1.Tick
Dim t As New Thread(AddressOf SomeTask)
t.Start()
End Sub
Private Sub SomeTask()
'...
End Sub
vb.net Code:
Private Sub Timer1_Tick(ByVal sender As Object, _
ByVal e As EventArgs) Handles Timer1.Tick
ThreadPool.QueueUserWorkItem(AddressOf SomeTask)
End Sub
Private Sub SomeTask(ByVal data As Object)
'...
End Sub
Re: Timer multi-threading help
thanks. the links helped. i think i got it working