Using Console.WriteLine in a Timer why it would appear to exit?

一世执手 提交于 2019-12-07 14:41:11

问题


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



来源:https://stackoverflow.com/questions/18357256/using-console-writeline-in-a-timer-why-it-would-appear-to-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!