Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>Console.ReadKey()</code> method locks the <code>Console.InternalSyncObject</code> whereas the <code>Console.ReadLine()</code> method does not. When the <code>TimerCallBack()</code> method tries to write to the <code>Console</code> the <code>Thread</code> waits because the <code>Console.InternalSyncObject</code> is still locked. Therefore <code>GC.Collect()</code> is never called. As soon as you hit a key the lock is released and <code>GC.Collect()</code> is called.</p> <p>I changed your code to the following which doesn't lock the <code>Console.InternalSyncObject</code> and it only beeps once in Release and every 2 seconds in Debug.</p> <pre><code>private static void TimerCallback(Object o) { Console.Beep(); GC.Collect(); } </code></pre> <p>The reason the Console.WriteLine() waits is because it tries to acquire a lock on the <code>Console.InternalSyncObject</code> when creating the <code>Console.Out</code> <code>TextWriter</code> for the first time. </p> <p>Changing your code to the following works as expected as we create the <code>Console.Out</code> <code>TextWriter</code> before starting the timer.</p> <pre><code>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(); } </code></pre> <p>This is due to a change in .NET 4.5. More info <a href="http://blogs.microsoft.co.il/blogs/dorony/archive/2012/09/12/console-readkey-net-4-5-changes-may-deadlock-your-system.aspx" rel="noreferrer">here</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload