所以我希望暂停程序 5 秒钟,然后再继续程序的其余部分。这就是我目前所掌握的要点。
tickerStart = System.Environment.TickCount;
do
{
//this is part of my own library, it generates a shape in a different window
numbers.AddText(Convert.ToString(number), 100);
}
while (tickerStart < 5000);
numbers.AddRectangle(0, 0, 800, 600, Color.Black);
//This last line simply clears the screen
Console.Readkey();
本质上,我想在不同的窗口中生成一些文本,然后想在 5 秒后清除它。
在问题中提供的代码中,您没有更新tickerStart
因此while
循环中的条件永远不会更改。
作为基本修复 - 但不推荐 - 您应该执行以下操作:
tickerStart = System.Environment.TickCount;
do
{
numbers.AddText(Convert.ToString(number), 100);
}
while (System.Environment.TickCount - tickerStart < 5000);
numbers.AddRectangle(0, 0, 800, 600, Color.Black);
但是,不建议使用此代码,因为它会阻止 UI 线程,因此 UI 在代码运行时不会更新。
相反,您需要使用某种计时器来完成此操作。
我建议使用Microsoft的反应式框架(NuGet "Rx-WinForms"或"Rx-WPF")。我假设 Winforms 具有以下代码:
Observable
.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(0.1)) //start immediately, then every 0.1s
.Take(50) // 5 seconds = 50 x 0.1s
.ObserveOn(this)
.Subscribe(
n => numbers.AddText(Convert.ToString(number), 100), //each timer tick
() => numbers.AddRectangle(0, 0, 800, 600, Color.Black)); //at end
如果您使用的是 WPF,则.ObserveOn(this)
将更改为 .ObserveOnDispatcher()
。
请注意 - 这不会延迟您的程序。如果您尝试延迟 UI 将不会更新。因此,您需要将接下来需要运行的代码放入() => { /* finally */}
代码块中。