In the application I'm currently working on I needed not only to use threading (some real intense processes) but I needed to be able to pause said thread then restart it when a condition was met.
After some testing, trial & error, and researching I found a solution to my quandry; To stop and start a thread (this example uses the click of a button but can be implemented in several ways). Of course you have to have your imports
Then declare the variables you need
Private m_Thread as Thread
You need a method to start the thread, this example does it in the form load event
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Make a new counter object. Dim new_counter As New Counter(Me)
' Make the thread to run the object's Run method. m_Thread = New Thread(AddressOf new_counter.Run)
' Make this a background thread so it automatically ' ends when the form's thread ends. m_Thread.IsBackground = True m_thread.Start Button1.Enabled = False Button2.Enabled = True End Sub
The following procedure checks to see if the thread was ever started (Unstarted Property) and that it isnt running (ThreadState Property) then determines whether to start or resume the thread
Private Sub Button1_Click(ByVal sender as Object, ByVal e As System.EventArgs) Handles Button1.Click If (m_Thread.ThreadState And ThreadState.Unstarted) <> _ 0 Then ' The thread has never been started. Start it. m_Thread.Start() Else ' The thread is paused. Resume it. m_Thread.Resume() End If
Button1.Enabled = True Button2.Enabled = False End Sub
Then finally, the procedure to pause the thread (once again in a button click event)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click ' Suspend the thread. Debug.WriteLine("Suspending thread") m_Thread.Suspend()
Button1.Enabled = False Button2.Enabled = True End Sub
Thats it, check to see if the thread has either been started before or if its running, if both are true then start the thread, otherwise resume the thread.