Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 ("C:/shared/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 ();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement