Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitlePause and resume a thread in VB.NET
DescriptionThis example shows how to pause and resume a thread in VB.NET.
Keywordsthread, multi-threading, SyncLock, asynchronous, threading, pause, resume, suspend
CategoriesVB.NET
 
When the program starts, it creates a new Counter object and a Thread, initializing it to execute the Counter's Run method.

The program sets the Thread's IsBackground property to True so it will automatically stop when the program's main thread stops. If you don't do this, the Thread will keep running until its Run method exits (which it never does so it would run until it reached an overflow problem).

When the user clicks the Start Thread button, the program starts the thread. If the Thread's ThreadState property indicates that it has never been started, the program calls its Start method. If ThreadState does not indicate that the Thread has never been started, the Thread has been suspended so the program calls its Resume method.

When the user clicks the Stop Thread button, the program calls the Thread's Suspend method.

 
Imports System.Threading
...
' Keep track of the thread so we can control it.
Private m_Thread As Thread

' This value is incremented by the thread.
Public Value As Integer = 0

' Make the thread but don't start it yet.
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

    btnStopThread.Enabled = False
    btnStartThread.Enabled = True
End Sub

' Start the thread.
Private Sub btnStartThread_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnStartThread.Click
    Debug.WriteLine("Starting thread")
    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

    btnStopThread.Enabled = True
    btnStartThread.Enabled = False
End Sub

Private Sub btnStopThread_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnStopThread.Click
    ' Suspend the thread.
    Debug.WriteLine("Suspending thread")
    m_Thread.Suspend()

    btnStopThread.Enabled = False
    btnStartThread.Enabled = True
End Sub
 
A Counter object displays its name and a count in the Debug window. The count comes from the form's Value variable.

The Run method enters an infinite loop. It sleeps for 1 second and then uses a SyncLock statement to get a lock on the form. This doesn't do anything to the form, it just means no other thread can lock the form object until we release the lock. To see why this is important, suppose the form's Value variable holds the value 1. Then suppose two threads are running and both enter this section of code at approximately the same time and follow this sequence of events:

  • Object 1 increments the form's Value property to 2.
  • Object 2 increments the form's Value property to 3.
  • Object 1 displays the form's Value property 3.
  • Object 2 displays the form's Value property 3.

Instead of displaying the value 2 and then 3, both of the threads display the value 3.

After it locks the form object, the Counter increments Value and displays the new value in the Output window. It then uses the End SyncLock statement to release its lock.

If another thread reaches its SyncLock statement while this object holds a lock on the form, the second object waits until the lock is released.

 
' This class's Run method displays a count in the Output
' window.
Public Class Counter
    ' The form that owns the Value variable.
    Private m_MyForm As Form1

    Public Sub New(ByVal my_form As Form1)
        m_MyForm = my_form
    End Sub

    ' Count off seconds in the Output window.
    Public Sub Run()
        Try
            Do
                ' Wait 1 second.
                Thread.Sleep(1000)

                ' Lock the form object. This doesn't do
                ' anything
                ' to the form, it just means no other
                ' thread can
                ' lock the form object until we release the
                ' lock.
                SyncLock m_MyForm
                    ' Increment the form's Value.
                    m_MyForm.Value += 1

                    ' Write the value.
                    Debug.WriteLine("Thread: " & _
                        m_MyForm.Value)
                End SyncLock
            Loop
        Catch ex As ThreadAbortException
            ' This happens when the main program aborts the
            ' thread.
            Debug.WriteLine("Thread aborting")
        Catch ex As Exception
            ' An unexpected error.
            Debug.WriteLine("Unexpected error in thread" & _
                vbCrLf & _
                ex.Message)
        End Try
    End Sub
End Class
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated