Using Console.WriteLine in a Timer why it would ap

2019-05-15 20:00发布

问题:

I have a console application,when I use Console.ReadLine(),the application will show "Hello World".why Console.ReadKey() can't?`

static void Main(string[] args)
{
     System.Timers.Timer timer = new System.Timers.Timer(1000);
     timer.Elapsed += timer_Elapsed;
     timer.Enabled = true;

     Console.ReadKey();// When use ReadLine() work fine;
}

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
     Console.WriteLine("Hello World");
}

Fixed:http://support.microsoft.com/kb/2805221

回答1:

Console.ReadKey .NET 4.5 changes may deadlock your system

Console.ReadKey now locks a synchronization object which gets locked when you attempt to access stderr for the first time. Therefore, the solution is simple, we need to cause Console.Error to initialize before the call to Console.ReadKey.

update:An update is available for the .NET Framework 4.5 in Windows 7 SP1, Windows Server 2008 R2 SP1, Windows Server 2008 SP2, and Windows Vista SP2: May 2013



回答2:

I ran your code and it works for both Console.ReadKey() and Console.ReadLine()



回答3:

In this application, the Timer runs on an other thread. On the other hand in parallel your main thread executes Console.ReadKey() or Console.ReadLine() and the Timer's thread goes on running paralelly and writes "Hello World" periodically until the main thread exits.

If you put Console.ReadKey() the main thread will exit after a keypress from keyboard.
If you put Console.ReadLine() the main thread will exit after pressing the Enter key from keyboard.

For more information about types of Timers: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx