Crear y lanzar un thread

2017 vistas

Para crear un thread tendremos que usar la clase System.Threading.Thread.

Veamos un ejemplo:

Consideremos que disponemos de un Form. Necesitamos declarar nuestro objeto thread en el interior de éste.



vbnet
  1. Imports System.Threading
  2.  
  3. Public Class Threads
  4.     Inherits System.Windows.Forms.Form
  5.  
  6.     '........
  7.     Private _threadCalculs1 As Thread
  8.  
  9. End Class



La función ejecutada por el thread viene impuesta por el framework de .NET, System.Threading.ThreadStart. Es una función sin parámetros y que no devuelve nada. Podemos declararla asà en nuestro Form.



vbnet
  1. Imports System.Threading
  2.  
  3. Public Class Threads
  4.     Inherits System.Windows.Forms.Form
  5.  
  6.     '........
  7.  
  8.     Private Sub ThrFunc1()
  9.     ' código del thread. Calculs es una función cualquiera de nuestro Form
  10.         Try
  11.             Calculs(1000)
  12.         Catch ex As Exception
  13.             Debug.WriteLine(ex.ToString())
  14.         End Try
  15.     End Sub
  16.  
  17. End Class



Para arrancar el thread usaremos la función Start de la clase Thread.



vbnet
  1. Imports System.Threading
  2.  
  3. Public Class Threads
  4.     Inherits System.Windows.Forms.Form
  5.  
  6.     ' ........
  7.    
  8.     Private Sub StartThread()
  9.         ' ThrFunc es la función ejecutada por el thread. 
  10.         _threadCalculs1 = New Thread(AddressOf ThrFunc1)
  11.         ' es práctico dar nombre a los threads, sobretodo si creamos varios.
  12.         _threadCalculs1.Name = "Thread1"
  13.         ' arrancamos el thread.
  14.         _threadCalculs1.Start()
  15.     End Sub
  16. End Class