I know this might be strange but I have a timer and I have an event handler for Elapsed event that writes on Console, but when I start the application, the timer start properly, the event fire properly, too. However, the result doesn't show in console except after I press a button, which made me put two Console.ReadKey()
so the application won't terminate.
Here is the code in Program.cs
:
static void Main(string[] args)
{
Timer timer = new Timer(100);
timer.Elapsed += new ElapsedEventHandler(WriteOnConsole);
timer.Start();
Console.ReadKey();
Console.ReadKey();
}
static void WriteOnConsole(object source, ElapsedEventArgs e)
{
Console.WriteLine("A B C D");
}
Please inform me if I haven't mentioned enough information.
The ReadKey()
blocks the WriteLine()
. After you pressed one key, the first ReadKey
is finished and the pending writes to the console are flushed.
As this obviously only is a small sample to demonstrate the problem it is hard to suggest a better alternative.
One could be to use some sort of wait handle to exit the application only when a certain condition is met.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With