Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4.  
  5. namespace Recetas.CSharp.Cap04
  6. {
  7.     public sealed class AccesoArchivoConMonitor
  8.     {
  9.         public static object locker = new Object();
  10.        
  11.         public static void EscritirArchivo()
  12.         {
  13.             Thread.Sleep (1000);
  14.            
  15.             string nombreThread = Thread.CurrentThread.Name;
  16.            
  17.             Console.WriteLine ("\nEjecutándose el thread `{0}`", nombreThread);
  18.            
  19.             // Sección crítica:
  20.             Monitor.Enter (locker);
  21.             try
  22.             {
  23.                 using ( StreamWriter sw = new StreamWriter ("C:/shared/nombres-threads.txt", true))
  24.                 {
  25.                     sw.WriteLine (nombreThread);
  26.                 }
  27.             }
  28.             catch (Exception e)
  29.             {
  30.                 Console.WriteLine ("Mensaje excepción: {0}", e.Message);
  31.             }
  32.             finally
  33.             {
  34.                 Monitor.Exit (locker);
  35.                 Console.WriteLine ("El thread `{0}` ha finalizado su ejecución.", nombreThread);
  36.             }
  37.         }
  38.        
  39.         public static void Main()
  40.         {
  41.             for (int i = 1; i <= 5; ++i)
  42.             {
  43.                 Thread thread = new Thread (EscritirArchivo);
  44.                 thread.Name = string.Concat( "Thread - ", i);
  45.                 thread.Start ();
  46.             }
  47.            
  48.             Console.ReadLine ();
  49.         }
  50.     }
  51. }