【发布时间】:2017-04-23 19:36:28
【问题描述】:
我在 Visual Studio 2008、C# 和 .NET Framework 3.5 中有一个控制台应用程序。
当应用程序完成所有我想做的事情时,当用户按下一个键或几分钟后自动关闭窗口。
所以在我的申请结束时我会这样做:
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
public static int Main(string[] args)
{
// Do some stuff
Console.WriteLine("Press any key to close this window.");
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 5000;
myTimer.Start();
Console.ReadKey();
return 0;
}
private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
myTimer.Stop();
Environment.Exit(0);
}
这里的问题是窗口在 x 分钟过去后没有关闭,甚至计时器事件也从未引发,因为程序被阻止等待键 (ReadKey)。
那该怎么做呢?
【问题讨论】:
-
您使用了错误类型的计时器,您不能在这样的控制台应用程序中使用
System.Windows.Forms.Timer,您需要一个不依赖于“UI 线程”的计时器,例如 @ 987654323@
标签: c# visual-studio-2008 timer console-application