Crear y lanzar un thread

2055 vistas

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

Veamos un ejemplo:

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



csharp
  1. using System.Threading;
  2.  
  3. public class Threads : System.Web.Form
  4. {
  5.   // ........
  6.   private Thread _threadCalculs1;
  7. }



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.



csharp
  1. using System.Threading;
  2. public class Threads : System.Windows.Forms.Form
  3. {
  4.   // ........
  5.   private void ThrFunc1()
  6.   {
  7.     // código del thread. Calculs es una función cualquiera de nuestro Form
  8.     try
  9.     {
  10.       Calculs(1000) ;
  11.     }
  12.     catch (Exception ex)
  13.     {
  14.       Debug.WriteLine(ex.ToString());
  15.     }
  16.   }
  17. }



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



csharp
  1. using System.Threading;
  2. public class Threads : System.Windows.Forms.Form
  3. {
  4.   // ........
  5.   private void StartThread()
  6.   {
  7.     // ThrFunc es la función ejecutada por el thread.
  8.     _threadCalculs1 = new Thread(new ThreadStart(ThrFunc1));
  9.     // es práctico dar nombre a los threads, sobretodo si creamos varios.
  10.     _threadCalculs1.Name = "Thread1";
  11.     // arrancamos el thread.
  12.     _threadCalculs1.Start();
  13.   }
  14. }