Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 9, 2015 12:55
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/6ac114efcb1d5f308f93 to your computer and use it in GitHub Desktop.
Save Fhernd/6ac114efcb1d5f308f93 to your computer and use it in GitHub Desktop.
Uso de la clase `ManualResetEventSlim` en C#.
// OrtizOL - xCSw - http://ortizol.blogspot.com
using System;
using System.Threading;
namespace Receta.Multithreading.R0505
{
public class NotificacionMultiplesThreads
{
// Instancia de `ManualResetEventSlim` para el control de la
// ejecución de múltiples threads:
public static ManualResetEventSlim evento = new ManualResetEventSlim(false);
public static void Main(string[] args)
{
Console.WriteLine(Environment.NewLine);
// Creación de 3 threads:
Thread t1 = new Thread(() => Proceso("Thread1", 5));
Thread t2 = new Thread(() => Proceso("Thread2", 6));
Thread t3 = new Thread(() => Proceso("Thread3", 12));
// Inicio de la ejecución de los threads:
t1.Start();
t2.Start();
t3.Start();
Thread.Sleep(TimeSpan.FromSeconds(6));
// Tiempo de espera en `Main`:
Console.WriteLine("\nDesde el thread `Main` se da continución a los threads: `evento.Set()`.\n");
evento.Set();
Thread.Sleep(TimeSpan.FromSeconds(2));
evento.Reset();
Console.WriteLine("\nSe envía una notificación de suspensión de la ejecución de los 3 threads: `evento.Reset()`.\n");
Thread.Sleep(TimeSpan.FromSeconds(10));
Console.WriteLine("\nUna nueva señal de continuación de la ejecución de los 3 threads: `evento.Set()`.\n");
evento.Set();
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("\nSeñal final de suspensión: `evento.Reset()`.");
evento.Reset();
// BUENA PRÁCTICA: Invocar `evento.Dispose()` una vez se haya
// terminado con el uso del objeto `ManualResetEventSlim`:
evento.Dispose();
Console.WriteLine(Environment.NewLine);
}
public static void Proceso(String nombreThread, int tiempoEspera)
{
Console.WriteLine("El thread `{0}` ha iniciado su ejecución.", nombreThread);
Console.WriteLine("El thread `{0}` está a punto de suspenderse por {1} segundos.",
nombreThread, tiempoEspera);
Thread.Sleep(TimeSpan.FromSeconds(tiempoEspera));
Console.WriteLine("El thread `{0}` se halla en espera de notificación para continuar su ejecución.",
nombreThread);
evento.Wait();
Console.WriteLine("El thread `{0}` ha sido notificado y continua su ejecución.", nombreThread);
Console.WriteLine("El thread `{0}` ha finalizado su ejecución.", nombreThread);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment