Console.ReadKey vs Console.ReadLine with a Timer Console.ReadKey vs Console.ReadLine with a Timer multithreading multithreading

Console.ReadKey vs Console.ReadLine with a Timer


The Console.ReadKey() method locks the Console.InternalSyncObject whereas the Console.ReadLine() method does not. When the TimerCallBack() method tries to write to the Console the Thread waits because the Console.InternalSyncObject is still locked. Therefore GC.Collect() is never called. As soon as you hit a key the lock is released and GC.Collect() is called.

I changed your code to the following which doesn't lock the Console.InternalSyncObject and it only beeps once in Release and every 2 seconds in Debug.

private static void TimerCallback(Object o){    Console.Beep();    GC.Collect();}

The reason the Console.WriteLine() waits is because it tries to acquire a lock on the Console.InternalSyncObject when creating the Console.Out TextWriter for the first time.

Changing your code to the following works as expected as we create the Console.Out TextWriter before starting the timer.

public static void Main(){    Console.WriteLine("Loaded");    Timer t = new Timer(TimerCallback, null, 0, 2000);    Console.ReadKey();}private static void TimerCallback(Object o){    Console.WriteLine("In TimerCallback: " + DateTime.Now);    GC.Collect();}

This is due to a change in .NET 4.5. More info here