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.     public sealed class EstadosThread
  7.     {
  8.         public static void Main()
  9.         {
  10.             Console.WriteLine ("\nInicio de la aplicación...");
  11.            
  12.             // Creación de threads:
  13.             Thread t1 = new Thread (new ThreadStart (ImprimirNumerosConEstado));
  14.             Thread t2 = new Thread (new ThreadStart (Tarea));
  15.            
  16.             Console.WriteLine ("\nEstado actual del thread `t1`: {0}", t1.ThreadState.ToString());
  17.            
  18.             // Inicialización de los threads:
  19.             t1.Start();
  20.             t2.Start();
  21.            
  22.             for (int i = 1; i < 30; ++i)
  23.             {
  24.                 Console.WriteLine ("Estado actual del thread `t1`: {0}", t1.ThreadState.ToString());
  25.             }
  26.            
  27.             // Pausa por 6 segundos del thread Main:
  28.             Thread.Sleep (TimeSpan.FromSeconds (6));
  29.            
  30.             // Aborta el thread `t1`:
  31.             t1.Abort();
  32.            
  33.             // Presentación de resultados:
  34.             Console.WriteLine ("\nUn thread ha sido abortado.");
  35.             Console.WriteLine ("Estado del thread `t1`: {0}", t1.ThreadState.ToString());
  36.             Console.WriteLine ("Estado del thread `t2`: {0}\n", t2.ThreadState.ToString());
  37.         }
  38.        
  39.         private static void Tarea()
  40.         {
  41.             Thread.Sleep (TimeSpan.FromSeconds (2));
  42.         }
  43.        
  44.         private static void ImprimirNumerosConEstado()
  45.         {
  46.             Console.WriteLine ("\nInicio del método `ImprimirNumerosConEstado`...");
  47.            
  48.             Console.WriteLine ("\nEstado actual thread actual: {0}", Thread.CurrentThread.ThreadState.ToString());
  49.            
  50.             for (int i = 1; i < 10; ++i)
  51.             {
  52.                 Thread.Sleep (TimeSpan.FromSeconds (2));
  53.                
  54.                 Console.WriteLine ("Valor de `i`: {0}", i.ToString());
  55.             }
  56.         }
  57.     }
  58. }