Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created August 21, 2014 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/6de2892dbbb983009d0c to your computer and use it in GitHub Desktop.
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.
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