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

1 c# sleep timer delay console-application

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

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

Run Code Online (Sandbox Code Playgroud)

小智 5

一个简单的方法是使用

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...)
Run Code Online (Sandbox Code Playgroud)

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