Timer event handler does not write to the console

I know this may be strange, but I have a timer, and I have an event handler for the Elapsed event, which is written to the console, but when I launch the application, the timer starts correctly, the event fires correctly. However, the result is not displayed in the console, except that I press the button, which forced me to put two Console.ReadKey() so that the application does not end.

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("ABCD"); } 

Please let me know if I have not mentioned enough information.

+4
source share
3 answers

ReadKey() blocks WriteLine() . After you press one key, the first ReadKey will be completed, and pending writes to the console will be reset.

Since this is obviously only a small sample to demonstrate the problem, it is difficult to offer a better alternative.

One could use some wait descriptor to exit the application only if a certain condition is met.

+8
source

I saw this in another question - you don’t even need a timer, just any two streams where one stream reads from the console and the other writes.

It seems that the initialization for Console somewhat broken - the first call will effectively release the lock until it is completed, preventing access to any other console.

If you write:

 Console.WriteLine("Starting"); 

at the beginning of your code, everything will be fine, for example. This is not like ReadKey (or any other read operation) blocks the entire output of the console as a whole - this is only in the first call.

+2
source

Try to write an empty line from the 1st stream, first of all, by initializing the console:

 static void Main(string[] args) { Console.Write(string.Empty); 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("ABCD"); } 
+2
source

All Articles