Thread Looping

fredriko

Active member
Joined
Jun 3, 2004
Messages
35
Programming Experience
10+
Does anybody know how I can put a method running in a seperate thread into a wait loop without consuming my CPU? I have created a method called ProcessJobs. This method runs on a seperate thread and waits for a flag to be set true. Upon the flag being set to true, tasks are performed and the flag is reset to false. The problem I am having is that while waiting for the flag to be set to true my CPU utilisation is high slowing my computer down even though my application in reality is doing nothing other than loop. Does any body know how I could get around this?
I use the following code to start the method
VB.NET:
m_ProcessThread = New Threading.Thread(AddressOf ProcessJobs)
m_ProcessThread.Name = "Process Jobs"
m_ProcessThread.Start()
This is the method code
VB.NET:
private sub ProcessJobs
    while not m_Cancelled
        while not m_StartProcess
            'loop until we get a start signal
        loop
        'Perform some actions and wait for the next signal
        'Reset the start flag
        m_StartProcess=False
    loop
end sub
 
While...Loop? That is not valid VB.Net code, but I get what you want to do, here is an example using the AutoResetEvent, I set up 2 buttons - each time first button (ActionButton) is clicked the work of one loop is done, second button click (FinishButton) signals the thread to finish off:
VB.NET:
Private Sub frmDiv_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
    Dim m_ProcessThread As New Threading.Thread(AddressOf ProcessJobs)
    m_ProcessThread.Name = "Process Jobs"
    m_ProcessThread.Start()
End Sub
 
Private wh As New Threading.AutoResetEvent(False)
Private threadabort As Boolean
 
Private Sub ActionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActionButton.Click
    wh.Set()
End Sub
 
Private Sub FinishButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FinishButton.Click
    threadabort = True
    wh.Set()
End Sub
 
Private Sub ProcessJobs()
    Do
        [COLOR=darkgreen]'wait until we get a start signal[/COLOR]
        wh.WaitOne()
        [COLOR=darkgreen]'exit thread if requested[/COLOR]
        If threadabort Then Exit Do
        [COLOR=darkgreen]'Perform some actions and wait for the next signal[/COLOR]
        Static counter As Integer
        counter += 1
        MsgBox(counter.ToString)
    Loop
    MsgBox("thread finished")
End Sub
 
Back
Top