Created
August 21, 2014 14:04
-
-
Save Fhernd/6de2892dbbb983009d0c to your computer and use it in GitHub Desktop.
Uso de la clase Monitor para controlar el acceso simultáneo a un recurso compartido.
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.Multithreading.Cap04.R0110 | |
{ | |
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:/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