Demonstrates using threads in a GUI : GUI Thread « GUI « VB.Net Tutorial






'Visual Basic(R) 2005 for Programmers (2nd Edition) (Deitel Developer Series) (Paperback)
'by Harvey M. Deitel (Author), Paul J. Deitel (Author)

'Publisher: Prentice Hall PTR; 2 edition (June 6, 2006)
'Language: English
'ISBN-10: 013225140X
'ISBN-13: 978-0132251402



'**************************************************************************
'* (C) Copyright 1992-2006 by Deitel & Associates, Inc. and               *
'* Pearson Education, Inc. All Rights Reserved.                           *
'*                                                                        *
'* DISCLAIMER: The authors and publisher of this book have used their     *
'* best efforts in preparing the book. These efforts include the          *
'* development, research, and testing of the theories and programs        *
'* to determine their effectiveness. The authors and publisher make       *
'* no warranty of any kind, expressed or implied, with regard to these    *
'* programs or to the documentation contained in these books. The authors *
'* and publisher shall not be liable in any event for incidental or       *
'* consequential damages in connection with, or arising out of, the       *
'* furnishing, performance, or use of these programs.                     *
'**************************************************************************


Imports System.Threading
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms

public class UsingThreadInGUI
   public Shared Sub Main
        Application.Run(New frmGUIThreads)
   End Sub
End class


Public Class frmGUIThreads
   Private letter1 As RandomLetters ' first randomLetters object
   Private letter2 As RandomLetters ' second randomLetters object
   Private letter3 As RandomLetters ' third randomLetters object

   Private Sub frmGUIThreads_Load(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load

      ' create first thread
      letter1 = New RandomLetters(lblThread1)
      Dim firstThread As New Thread(New ThreadStart( _
         AddressOf letter1.Run))
      firstThread.Name = "Thread 1"
      firstThread.Start()

      ' create second thread
      letter2 = New RandomLetters(lblTread2)
      Dim secondThread As New Thread(New ThreadStart( _
         AddressOf letter2.Run))
      secondThread.Name = "Thread 2"
      secondThread.Start()

      ' create third thread
      letter3 = New RandomLetters(lblThread3)
      Dim thirdThread As New Thread(New ThreadStart( _
         AddressOf letter3.Run))
      thirdThread.Name = "Thread 3"
      thirdThread.Start()
   End Sub ' frmGUIThreads_Load

   ' close all threads associated with this application
   Private Sub frmGUIThreads_FormClosing(ByVal sender As System.Object, _
      ByVal e As System.Windows.Forms.FormClosingEventArgs) _
      Handles MyBase.FormClosing
      System.Environment.Exit(System.Environment.ExitCode)
   End Sub ' frmGUIThreads_FormClosing

   Private Sub chkThread_CheckedChanged(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles chkThread1.CheckedChanged, _
      chkThread3.CheckedChanged, chkThread2.CheckedChanged
      If sender.Equals(chkThread1) Then
         letter1.Toggle()
      ElseIf sender.Equals(chkThread2) Then
         letter2.Toggle()
      ElseIf sender.Equals(chkThread3) Then
         letter3.Toggle()
      End If
   End Sub ' chkThread_CheckedChanged
End Class ' frmGUIThreads



Public Class RandomLetters
   Private Shared generator As New Random() ' for random letters
   Private suspended As Boolean = False ' true if thread is suspended
   Private output As Label ' Label for output
   Private threadName As String ' name of the current thread

   ' constructor
   Public Sub New(ByVal label As Label)
      output = label
   End Sub ' New

   ' delegate that allows method DisplayCharacter to be called
   ' in the thread that creates and maintains the GUI       
   Delegate Sub DisplayDelegate(ByVal displayChar As Char)

   ' method DisplayCharacter sets the Label's Text property
   ' in a thread-safe manner
   Private Sub DisplayCharacter(ByVal displayChar As Char)
      ' output character in Label
      output.Text = threadName + ": " + displayChar
   End Sub ' DisplayCharacter

   ' place random characters in GUI
   Public Sub Run()
      ' get name of executing thread
      threadName = Thread.CurrentThread.Name

      While True ' infinite loop; will be terminated from outside
         ' sleep for up to 1 second
         Thread.Sleep(generator.Next(1001))

         SyncLock Me ' obtain lock
            While suspended ' loop until not suspended
               Monitor.Wait(Me) ' suspend thread execution
            End While
         End SyncLock

         ' select random uppercase letter
         Dim displayChar As Char = ChrW(generator.Next(26) + 65)

         ' display character on corresponding Label
         output.Invoke(New DisplayDelegate(AddressOf DisplayCharacter), _
            New Object() {displayChar})
      End While
   End Sub ' Run

   ' change the suspended/running state
   Public Sub Toggle()
      suspended = Not suspended ' toggle bool controlling state

      ' change label color on suspend/resume
      If suspended Then
         output.BackColor = Color.Red
      Else
         output.BackColor = Color.LightGreen
      End If

      SyncLock Me ' obtain lock
         If Not suspended Then ' if thread resumed
            Monitor.Pulse(Me)
         End If
      End SyncLock
   End Sub ' Toggle
End Class ' RandomLetters


<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Public Class frmGUIThreads
   Inherits System.Windows.Forms.Form

   'Form overrides dispose to clean up the component list.
   <System.Diagnostics.DebuggerNonUserCode()> _
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing AndAlso components IsNot Nothing Then
         components.Dispose()
      End If
      MyBase.Dispose(disposing)
   End Sub

   'Required by the Windows Form Designer
   Private components As System.ComponentModel.IContainer

   'NOTE: The following procedure is required by the Windows Form Designer
   'It can be modified using the Windows Form Designer.  
   'Do not modify it using the code editor.
   <System.Diagnostics.DebuggerStepThrough()> _
   Private Sub InitializeComponent()
      Me.lblThread1 = New System.Windows.Forms.Label
      Me.lblTread2 = New System.Windows.Forms.Label
      Me.lblThread3 = New System.Windows.Forms.Label
      Me.chkThread1 = New System.Windows.Forms.CheckBox
      Me.chkThread2 = New System.Windows.Forms.CheckBox
      Me.chkThread3 = New System.Windows.Forms.CheckBox
      Me.SuspendLayout()
      '
      'lblThread1
      '
      Me.lblThread1.AutoSize = True
      Me.lblThread1.BackColor = System.Drawing.Color.LightGreen
      Me.lblThread1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
      Me.lblThread1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblThread1.Location = New System.Drawing.Point(13, 9)
      Me.lblThread1.Name = "lblThread1"
      Me.lblThread1.Size = New System.Drawing.Size(63, 18)
      Me.lblThread1.TabIndex = 0
      Me.lblThread1.Text = "Thread 1:"
      '
      'lblTread2
      '
      Me.lblTread2.AutoSize = True
      Me.lblTread2.BackColor = System.Drawing.Color.LightGreen
      Me.lblTread2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
      Me.lblTread2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblTread2.Location = New System.Drawing.Point(13, 34)
      Me.lblTread2.Name = "lblTread2"
      Me.lblTread2.Size = New System.Drawing.Size(63, 18)
      Me.lblTread2.TabIndex = 1
      Me.lblTread2.Text = "Thread 2:"
      '
      'lblThread3
      '
      Me.lblThread3.AutoSize = True
      Me.lblThread3.BackColor = System.Drawing.Color.LightGreen
      Me.lblThread3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
      Me.lblThread3.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.lblThread3.Location = New System.Drawing.Point(13, 59)
      Me.lblThread3.Name = "lblThread3"
      Me.lblThread3.Size = New System.Drawing.Size(63, 18)
      Me.lblThread3.TabIndex = 2
      Me.lblThread3.Text = "Thread 3:"
      '
      'chkThread1
      '
      Me.chkThread1.AutoSize = True
      Me.chkThread1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.chkThread1.Location = New System.Drawing.Point(116, 8)
      Me.chkThread1.Name = "chkThread1"
      Me.chkThread1.Size = New System.Drawing.Size(93, 20)
      Me.chkThread1.TabIndex = 3
      Me.chkThread1.Text = "Suspended"
      '
      'chkThread2
      '
      Me.chkThread2.AutoSize = True
      Me.chkThread2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.chkThread2.Location = New System.Drawing.Point(116, 33)
      Me.chkThread2.Name = "chkThread2"
      Me.chkThread2.Size = New System.Drawing.Size(93, 20)
      Me.chkThread2.TabIndex = 4
      Me.chkThread2.Text = "Suspended"
      '
      'chkThread3
      '
      Me.chkThread3.AutoSize = True
      Me.chkThread3.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
      Me.chkThread3.Location = New System.Drawing.Point(116, 58)
      Me.chkThread3.Name = "chkThread3"
      Me.chkThread3.Size = New System.Drawing.Size(93, 20)
      Me.chkThread3.TabIndex = 5
      Me.chkThread3.Text = "Suspended"
      '
      'frmGUIThreads
      '
      Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
      Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
      Me.ClientSize = New System.Drawing.Size(221, 86)
      Me.Controls.Add(Me.chkThread3)
      Me.Controls.Add(Me.chkThread2)
      Me.Controls.Add(Me.chkThread1)
      Me.Controls.Add(Me.lblThread3)
      Me.Controls.Add(Me.lblTread2)
      Me.Controls.Add(Me.lblThread1)
      Me.Name = "frmGUIThreads"
      Me.Text = "GUI Threads"
      Me.ResumeLayout(False)
      Me.PerformLayout()

   End Sub
   Friend WithEvents lblThread1 As System.Windows.Forms.Label
   Friend WithEvents lblTread2 As System.Windows.Forms.Label
   Friend WithEvents lblThread3 As System.Windows.Forms.Label
   Friend WithEvents chkThread1 As System.Windows.Forms.CheckBox
   Friend WithEvents chkThread2 As System.Windows.Forms.CheckBox
   Friend WithEvents chkThread3 As System.Windows.Forms.CheckBox

End Class








14.91.GUI Thread
14.91.1.Create control in a separate threadCreate control in a separate thread
14.91.2.Thread Sleeps in a button's actionThread Sleeps in a button's action
14.91.3.Demonstrates using threads in a GUI