Created
June 26, 2014 04:43
-
-
Save Fhernd/41dde3081dbf957eac8f to your computer and use it in GitHub Desktop.
Demostración de uso de WaitOrTimerCallback en C#.
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.Threading; | |
namespace Recetas.Cap04 | |
{ | |
internal sealed class ManejadorSenializacion | |
{ | |
public static void Main() | |
{ | |
// Crea manejador del mecanismo de señalización: | |
AutoResetEvent are = new AutoResetEvent (false); | |
// Crea mensaje a pasar al método ManejadorEventos | |
// cuando este se ejecute: | |
string info = "AutoResetEvent generó una señal."; | |
// Registro del método ManejadorEventos a espera o | |
// una vez que AutoResetEvent emita una señal. El ciclo | |
// de tiempo es de 10 segundos. La operación de espera | |
// se realizará indefinidamente (false): | |
RegisteredWaitHandle manejador = ThreadPool.RegisterWaitForSingleObject ( | |
are, | |
new WaitOrTimerCallback (ManejadorEventos), | |
info, | |
10000, | |
false | |
); | |
Console.WriteLine ("Presione Enter para activar la señal de AutoResetEvent" + | |
"\no ingrese \"Cancelar\" para des-registrar la operación de espera."); | |
while ( Console.ReadLine ().ToUpper() != "CANCELAR") | |
{ | |
// Mientras que el usuario no decida ingresar "Cancelar" | |
// se activará una señal sobre AutoResetEvent; esto | |
// hará que el método ManejadorEventos se ejecute; además, | |
// de reestablecer para una próxima ejecución: | |
are.Set(); | |
} | |
// Des-registra el manejador de señalización: | |
Console.WriteLine ("\n\nRemoviendo el manejador de señalización..."); | |
manejador.Unregister (null); | |
Console.WriteLine ("\nEl método Main ha finalizado. Presione Enter para finalizar."); | |
Console.ReadLine (); | |
} | |
// Método que será ejecutado cada vez que una | |
// instancia de AutoResetEvent genere una señal o | |
// una cantidad de tiempo haya transcurrido: | |
private static void ManejadorEventos (object info, bool tiempoAgotado) | |
{ | |
// El mensaje a mostrar depende si el objeto AutoResetEvent ha | |
// generado una señal o el tiempo especificado se ha agotado: | |
if (tiempoAgotado) | |
{ | |
Console.WriteLine ("El tiempo se agotó a las {0}.", | |
DateTime.Now.ToString ("HH:mm:ss:ffff")); | |
} | |
else | |
{ | |
Console.WriteLine ("Estado `{1}` a las {0}.", | |
DateTime.Now.ToString ("HH:mm:ss:ffff"), info); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment