Ciao un esempio che mi e' stato utile per capire il funzionamento dei thread e' questo, e' molto semplice da capire:
codice:Option Explicit On Option Strict On Imports System.Threading ' ********************************************************************************************** ' * Created In VS2005 * ' * Example of multi or worker threading in VB.Net with start & stop of the worker thread * ' * With invoking to update progress bar & textbox * ' * Create a form with 2x buttons and 1x textbox & 1 x progress bar * ' * Modified from the MicroSoft Help So it actually works!! * ' ********************************************************************************************** Public Class Form1 Dim WorkerThread As Thread 'Create the worker thread Dim NewVal As Integer 'New Value of progress bar & textbox Dim StopThread As Boolean = True 'Boolean Value used to halt the endless loop Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If StopThread = False Then StopThread = True Else StopThread = False WorkerThread = New Thread(AddressOf ThreadTask) WorkerThread.IsBackground = True WorkerThread.Start() End If End Sub Private Sub ThreadTask() Dim ProgBarStep As Integer Dim RandomNo As New Random() Do Until StopThread = True ProgBarStep = ProgressBar1.Step * RandomNo.Next(-1, 2) NewVal = ProgressBar1.Value + ProgBarStep If NewVal > ProgressBar1.Maximum Then NewVal = ProgressBar1.Maximum ElseIf NewVal < ProgressBar1.Minimum Then NewVal = ProgressBar1.Minimum End If Me.ProgressBar1.Invoke(New MethodInvoker(AddressOf InvokeProgBar1)) Me.ProgressBar1.Invoke(New MethodInvoker(AddressOf InvokeTextBox1)) Thread.Sleep(100) Loop End Sub Private Sub InvokeProgBar1() Me.ProgressBar1.Value = CInt(NewVal) End Sub Private Sub InvokeTextBox1() Me.TextBox1.Text = CStr(NewVal) End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show("This is the main thread") End Sub End Class

Rispondi quotando