How do I stop a SLEEPing thread?

S

Scott M. Lyon

I've got an application that, in the main form, Starts up a thread. That
thread consists of an endless loop (a WHILE TRUE loop), at the end of each
iteration is a Sleep() command, so it will sleep for 5 seconds between each
run.


I need this thread to poll for some database changes, and update data on the
form when it does.


I've got that part working fine.


What I'm having a problem with, is when I change the value of one of the
controls on my form (in this case a combobox), I want to have it bump it out
of "sleep" mode before the 5 seconds has passed.

However, I cannot figure out how to do this.


Any ideas?



Oh, before it's suggested, I can't just reduce my sleep delay, as I don't
want to bring the database to it's knees from continually calling it.


Thanks!
-Scott
 
J

Jay B. Harlow [MVP - Outlook]

Scott,
Any ideas?
Rather then use Sleep, have you considered using a
System.Threading.AutoResetEvent object?

Your thread would call AutoResetEvent.WaitOne with a timeout value. While
your main thread would call AutoResetEvent.Set to release the thread early.

Something like (untested):

Private m_event As New AutoResetEvent(False)
Private m_wait As TimeSpan = TimeSpan.FromSeconds(5)

Public Sub WorkerThread(...)

Do While True
m_event.WaitOne(m_wait, False)
' do the database stuff
Loop

End Sub

Private Sub ComboBox_Changed(...)
m_event.Set()
End Sub

The m_event.WaitOne will wait 5 seconds or until m_event.Set is called which
ever comes first.

Hope this helps
Jay
 
S

Scott M. Lyon

That worked wonderfully! Thanks, Jay!


Jay B. Harlow said:
Scott,
Rather then use Sleep, have you considered using a
System.Threading.AutoResetEvent object?

Your thread would call AutoResetEvent.WaitOne with a timeout value. While
your main thread would call AutoResetEvent.Set to release the thread early.

Something like (untested):

Private m_event As New AutoResetEvent(False)
Private m_wait As TimeSpan = TimeSpan.FromSeconds(5)

Public Sub WorkerThread(...)

Do While True
m_event.WaitOne(m_wait, False)
' do the database stuff
Loop

End Sub

Private Sub ComboBox_Changed(...)
m_event.Set()
End Sub

The m_event.WaitOne will wait 5 seconds or until m_event.Set is called which
ever comes first.

Hope this helps
Jay
 

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