Keep It Under Control
After the thread is started, you have some control over the state of it by using methods of the Thread object. You can pause a thread's execution by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. If you wanted to slow down the addition of items to the listbox in the example above, place a call to the sleep method in this code:
Private Sub BackgroundProcess()
Dim i As Integer = 1
Do While True
ListBox1.Items.Add("Iterations: " + i)
i += 1
CurrentThread is a public static property that allows you to retrieve a reference to the currently running thread.
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt method.
Similar to Sleep and Interrupt are Suspend and Resume. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.
Lastly, Thread.Abort stops a thread from executing. In our simple example, we would want to add another button on the form that allows us to stop the process. To do this all we would have to do is call the Thread.Abort method as follows:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
This is where the power of multithreading can be seen. The UI seems responsive to the user because it is running in one thread and the background process is running in another thread. The cancel button immediately responds to the user's click event and processing stops.