VB.Net Tutorial/GUI/GUI Thread

Материал из VB Эксперт
Перейти к: навигация, поиск

Create control in a separate thread

Imports System.Threading
Imports System.Windows.Forms
public class AddControlInThread
   public Shared Sub Main
        Application.Run(New Form1)
   End Sub
End class
Public Class Form1
  Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
  Public Sub New()
    MyBase.New()
    "This call is required by the Windows Form Designer.
    InitializeComponent()
    "Add any initialization after the InitializeComponent() call
  End Sub
  "Form overrides dispose to clean up the component list.
  Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    If disposing Then
      If Not (components Is Nothing) Then
        components.Dispose()
      End If
    End If
    MyBase.Dispose(disposing)
  End Sub
  "Required by the Windows Form Designer
  Private components As System.ruponentModel.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.
  Friend WithEvents Button1 As System.Windows.Forms.Button
  Friend WithEvents Label1 As System.Windows.Forms.Label
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(8, 8)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(64, 32)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Test"
        "
        "Label1
        "
        Me.Label1.Location = New System.Drawing.Point(8, 64)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(272, 176)
        Me.Label1.TabIndex = 1
        "
        "Form1
        "
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Label1, Me.Button1})
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)
    End Sub
#End Region
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim t1 As New Thread(AddressOf makecontrol)
    t1.Start()     
    makecontrol()  
  End Sub
  Private Sub makecontrol()
    Dim x As New Button()
    x.Name = "btnNew"
    x.Visible = True
    Try
      Me.Controls.Add(x)
    Catch Ex As System.ArgumentException
      MessageBox.Show(Ex.Message)
    End Try
  End Sub
End Class

Demonstrates using threads in a GUI

"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.rupilerServices.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.ruponentModel.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

Thread Sleeps in a button"s action

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
public class SleepInButtonAction
   public Shared Sub Main
        Application.Run(New Form1)
   End Sub
End class
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button1.Click
        Threading.Thread.Sleep(3000)
        MsgBox("Good Morning")
    End Sub
End Class
<Global.Microsoft.VisualBasic.rupilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form
    "Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected 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.ruponentModel.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.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        "
        "Button1
        "
        Me.Button1.Location = New System.Drawing.Point(8, 8)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(168, 23)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Slow Greeting"
        Me.Button1.UseVisualStyleBackColor = True
        "
        "Form1
        "
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(216, 39)
        Me.Controls.Add(Me.Button1)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
        Me.MaximizeBox = False
        Me.Name = "Form1"
        Me.Text = "Pause Execution"
        Me.ResumeLayout(False)
    End Sub
    Friend WithEvents Button1 As System.Windows.Forms.Button
End Class