Created
June 15, 2014 11:56
-
-
Save Fhernd/27f2fe4ca95e4a40fca0 to your computer and use it in GitHub Desktop.
Demostración uso de TimerCallback y Timer 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 | |
{ | |
public sealed class ControlEjecucionPeriodica | |
{ | |
public static void Main() | |
{ | |
// Texto de estado: | |
string mensajeEstado = "Temporizador Expiró."; | |
Console.WriteLine ("\nCreación de instancia Timer a las {0}.", DateTime.Now.ToString ("HH:mm:ss.ffff")); | |
// Creación de Timer con método que se ejecuta cada un segundo: | |
using | |
( | |
Timer t = new Timer ( delegate (object s) | |
{ | |
Console.WriteLine ("{0} : {1}", DateTime.Now.ToString ("HH:mm:ss.ffff"), s); | |
}, mensajeEstado, 2000, 1000 ) | |
) | |
{ | |
int periodo; | |
// Lee el valor ingresado por el usuario. En caso de ser cero se detiene la ejecución. | |
// Cualquier valor inválido cancela la ejecución periódica: | |
do | |
{ | |
try | |
{ | |
periodo = Int32.Parse (Console.ReadLine ()); | |
} | |
catch (FormatException) | |
{ | |
periodo = 0; | |
} | |
// Cambia el intervalo de ejecución del método: | |
if (periodo > 0) | |
{ | |
t.Change (0, periodo); | |
} | |
} while (periodo > 0); | |
} | |
Console.WriteLine (); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment