Advertisement
Fhernd

ManejoExcepcionesThread.cs

Aug 28th, 2014
1,837
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.11 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.Multithreading.Cap01.R0111
  5. {
  6.     public sealed class ManejoExcepcionesThread
  7.     {
  8.         public static void Main()
  9.         {
  10.             Console.Title = "Manejo de Excepciones en Threads ---";
  11.             Console.WriteLine ();
  12.            
  13.             // Creación de thread con método adyacente que cuenta
  14.             // con manejo de excepciones interno:
  15.             Thread t1 = new Thread (ThreadConBloqueTryCatch);
  16.            
  17.             // Inicio de ejecución:
  18.             t1.Start();
  19.            
  20.             // Espera a que finalice para continuar:
  21.             t1.Join();
  22.            
  23.             // Demostración de ejecución de thread con método adyacente
  24.             // que no cuenta con su propia implementación para el
  25.             // manejo de excepción:
  26.             try
  27.             {
  28.                 Thread t2 = new Thread (ThreadSinBloqueTryCatch);
  29.                 t2.Start();
  30.             }
  31.             catch (Exception ex)
  32.             {
  33.                 Console.WriteLine ("Esta región de manejo de excepción no es alcanzada.");
  34.             }
  35.         }
  36.    
  37.         // Método que simula el lanzamiento de una excepción,
  38.         // pero que no cuenta con un bloque de try-catch:
  39.         private static void ThreadSinBloqueTryCatch()
  40.         {
  41.             Console.WriteLine ("Inicio de ejecución de un thread con fallas.");
  42.             Thread.Sleep (TimeSpan.FromSeconds (2));
  43.             throw new Exception ("¡Falla!");
  44.         }
  45.        
  46.         // Método que simula el lanzamiento de una excepción:
  47.         private static void ThreadConBloqueTryCatch()
  48.         {
  49.             try
  50.             {
  51.                 Console.WriteLine ("Inicio de ejecución de un thread con fallas.");
  52.                 Thread.Sleep (TimeSpan.FromSeconds (1));
  53.                 throw new Exception ("¡Falla!");
  54.             }
  55.             catch (Exception ex)
  56.             {
  57.                 Console.WriteLine ("Control sobre la excepción: {0}",
  58.                     ex.Message
  59.                 );
  60.             }
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement