1

I am trying to follow an example from a c# tutorial to trigger an event from the timer class when a certain amount of time has passed, however it doesn't seem to work.
Here is the code:

class Program
{
    static void Main(string[] args)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += new ElapsedEventHandler(TimerTickHandler);
        tmr.Interval = 1000;
        tmr.Enabled = true;
        Console.ReadKey();
    }

    public static void TimerTickHandler(object sender, ElapsedEventArgs e)
    {
        Console.Write("\rprinting: {0}", e.SignalTime.ToString());
    }

}

I attached the TimerTickHandler on to the elapsed event and after each second it should print the time to the screen, but I am not getting any output.
Any clue as to where I am going wrong?
Thanks for any help.

  • 2
    Yet another case of the .NET 4.5 change, ReadKey() takes a lock that prevents other threads from writing to the console. Your handler *does* execute, it just can't blabber to the console while it is in input mode. Set a breakpoint with the debugger to see this. – Hans Passant Mar 29 '13 at 11:37
  • I think I should report this as a bug, if it hasn't already been reported. – Matthew Watson Mar 29 '13 at 11:45

1 Answers1

3

Fix this by changing Console.ReadKey() to Console.ReadLine().

Here's a thread discussing why Console.ReadKey() has strange effects on multithreading in Console apps.

Essentially, Console.ReadKey() has taken a lock on an internal object which Console.Write() also tries to take a lock on. So when the timer goes off, the Console.Write() that you're using to report it blocks, because Console.ReadKey() has taken a lock on the same object that Console.Write() wants to use.

I consider this a bug in Console.ReadKey(). Holding a lock while waiting on I/O is always a bug, IMHO.

Also note that if you change the Console.Write() to Debug.WriteLine() and attach a debugger, it will also work even if you leave Console.ReadKey() in.

Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276