Crear y lanzar un thread
Artículo por Club Developers · 11 mayo 2006
2116 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.
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.
Para arrancar el thread usaremos la función Start de la clase Thread.
Veamos un ejemplo:
Consideremos que disponemos de un Form. Necesitamos declarar nuestro objeto thread en el interior de éste.
vbnet
Imports System.Threading Public Class Threads Inherits System.Windows.Forms.Form '........ Private _threadCalculs1 As Thread 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
Imports System.Threading Public Class Threads Inherits System.Windows.Forms.Form '........ Private Sub ThrFunc1() ' código del thread. Calculs es una función cualquiera de nuestro Form Try Calculs(1000) Catch ex As Exception Debug.WriteLine(ex.ToString()) End Try End Sub End Class
Para arrancar el thread usaremos la función Start de la clase Thread.
vbnet
Imports System.Threading Public Class Threads Inherits System.Windows.Forms.Form ' ........ Private Sub StartThread() ' ThrFunc es la función ejecutada por el thread. _threadCalculs1 = New Thread(AddressOf ThrFunc1) ' es práctico dar nombre a los threads, sobretodo si creamos varios. _threadCalculs1.Name = "Thread1" ' arrancamos el thread. _threadCalculs1.Start() End Sub End Class