Created
July 9, 2014 23:31
-
-
Save Fhernd/ef1f228695bc9f1d1bd1 to your computer and use it in GitHub Desktop.
Demostración del uso de los métodos Enter y Exit de la clase Monitor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Threading; | |
namespace Recetas.CSharp.Cap04 | |
{ | |
public sealed class AccesoArchivoConMonitor | |
{ | |
public static object locker = new Object(); | |
public static void EscritirArchivo() | |
{ | |
Thread.Sleep (1000); | |
string nombreThread = Thread.CurrentThread.Name; | |
Console.WriteLine ("\nEjecutándose el thread `{0}`", nombreThread); | |
// Sección crítica: | |
Monitor.Enter (locker); | |
try | |
{ | |
using ( StreamWriter sw = new StreamWriter ("F:/nombres-threads.txt", true)) | |
{ | |
sw.WriteLine (nombreThread); | |
} | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine ("Mensaje excepción: {0}", e.Message); | |
} | |
finally | |
{ | |
Monitor.Exit (locker); | |
Console.WriteLine ("El thread `{0}` ha finalizado su ejecución.", nombreThread); | |
} | |
} | |
public static void Main() | |
{ | |
for (int i = 1; i <= 5; ++i) | |
{ | |
Thread thread = new Thread (EscritirArchivo); | |
thread.Name = string.Concat( "Thread - ", i); | |
thread.Start (); | |
} | |
Console.ReadLine (); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment