Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.Multithreading.Cap01
  5. {
  6.     internal sealed class ImpresorNumeros
  7.     {
  8.         // Imprime los números del 0 al 9 introduciendo
  9.         // un retraso de 2 segundos por cada iteración
  10.         // del ciclo for:
  11.         private static void ImprimirNumerosConRetraso()
  12.         {
  13.             Console.WriteLine ("Inicio ejecución `ImprimirNumerosConRetraso`...");
  14.            
  15.             for (int i = 0; i < 10; ++i)
  16.             {
  17.                 // Retraso (pausa) de dos (2) segundos:
  18.                 Thread.Sleep (TimeSpan.FromSeconds (2));
  19.                 Console.WriteLine (i.ToString());
  20.             }
  21.         }
  22.        
  23.         public static void Main()
  24.         {
  25.             Console.WriteLine ("\nInicio ejecución Main...");
  26.            
  27.             // Creación Thread:
  28.             Thread nuevoThread = new Thread (ImprimirNumerosConRetraso);
  29.            
  30.             // Inicio Thread:
  31.             nuevoThread.Start();
  32.            
  33.             // Pausa el thread Main durante 6 segundos:
  34.             Thread.Sleep (TimeSpan.FromSeconds (6));
  35.            
  36.             // Aborta el thread `nuevoThread`:
  37.             nuevoThread.Abort();
  38.            
  39.             Console.WriteLine ("\nUn thread ha sido abortado.\n");
  40.            
  41.             // Crea un nuevo thread:
  42.             Thread nuevoThread2 = new Thread(ImprimirNumerosConRetraso);
  43.             nuevoThread2.Start();
  44.            
  45.             Console.WriteLine ("\nA punto de finalizar el thread Main\n");
  46.         }
  47.     }
  48. }