在Timer中使用Console.WriteLine为什么它会出现退出?

我有一个控制台应用程序,当我使用Console.ReadLine() ,应用程序将显示“Hello World”。为什么Console.ReadKey()不能?

 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"); } 

修复: http : //support.microsoft.com/kb/2805221

Console.ReadKey .NET 4.5更改可能会使系统死锁

Console.ReadKey现在锁定一个同步对象,当您第一次尝试访问stderr时,该对象将被锁定。 因此,解决方案很简单,我们需要在调用Console.ReadKey之前使Console.Error初始化。

更新: Windows 7 SP1,Windows Server 2008 R2 SP1,Windows Server 2008 SP2和Windows Vista SP2中的.NET Framework 4.5有更新:2013年5月

我运行了你的代码,它适用于Console.ReadKey()和Console.ReadLine()

在此应用程序中,Timer在另一个线程上运行。 另一方面,并​​行主线程执行Console.ReadKey()或Console.ReadLine(),并且Timer的线程继续运行并且定期写入“Hello World”,直到主线程退出。

如果您放置Console.ReadKey(),主键将在键盘按键后退出。
如果你输入Console.ReadLine(),主键将在键盘上按Enter键后退出。

有关计时器类型的更多信息: http : //msdn.microsoft.com/en-us/magazine/cc164015.aspx