在Timer中使用Console.WriteLine为何会退出? [英] Using Console.WriteLine in a Timer why it would appear to exit?

查看:105
本文介绍了在Timer中使用Console.WriteLine为何会退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

Console.ReadKey .NET 4.5的更改可能会导致系统死锁


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

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:< a href = http://support.microsoft.com/kb/2805221 rel = nofollow>已为Windows 7 SP1,Windows Server 2008 R2 SP1,Windows Server 2008 SP2,.NET Framework 4.5提供了更新,和Windows Vista SP2:2013年5月

这篇关于在Timer中使用Console.WriteLine为何会退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆