Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer event handler doesn't write on console

Tags:

c#

timer

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.

like image 480
Imad Nabil Alnatsheh Avatar asked Dec 12 '22 17:12

Imad Nabil Alnatsheh


1 Answers

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.

like image 106
Daniel Hilgarth Avatar answered Dec 31 '22 06:12

Daniel Hilgarth