首页 > 解决方案 > C# | 控制台应用程序 | 如何在执行下一行之前让程序等待(以毫秒为单位的时间)?

问题描述

我正在构建 ac# 控制台应用程序(.NET 框架),我想通过使用一些“动画”来制作一个漂亮的应用程序。我想打印“Press any Key to continue ...”并让它闪烁(出现然后消失,直到用户实际按下任何键。

 do
    {
       while (!Console.KeyAvailable)
         {
             Console.WriteLine("Press any key to continue...");

     /* here i want the program to wait for like 500ms,
      clear console and wait 500ms again before rewriting line*/

             Console.Clear();
         }
     } while (Console.ReadKey(true).Key != ConsoleKey.Escape);

标签: c#timerconsole-applicationdelaysleep

解决方案


一个简单的方法是使用

System.Threading.Thread.Sleep(5000); //暂停5秒。所以要闪光做到这一点。

Console.Clear();
Console.WriteLine("SomeText");
System.Threading.Thread.Sleep(1000);
Console.Clear();
Console.WriteLine("SomeText");
System.Threading.Thread.Sleep(1000);
/// ETC.. 

Console.WriteLine("Press Any key To Continue...)

这是一种简单的方法,有助于您理解编码。如果你想让它继续闪烁,那么只需将它放在一个循环内。然而!请记住,这有效地“暂停”了代码运行。因此,如果它在暂停线上,它将不允许用户按键继续。这就是为什么我把决赛Console.WriteLine();放在底部。如果您希望用户能够随时按下某个键并使其不断闪烁,那么您将不得不参与多线程,这可能比您感兴趣的要复杂一些。


推荐阅读