如何在等待ReadLine时更新C#Windows控制台应用程序中的当前行?

在C#中构建Windows控制台应用程序时,是否可以在等待readline时更新控制台中的行?

我目前的代码是:

do { Console.Clear(); Console.WriteLine("RA: " + scope.RightAscension); Console.WriteLine("Dec: " + scope.Declination); Console.WriteLine("Status: " + scope.Slewing); System.Threading.Thread.Sleep(1000); } while (true); 

是。 您可以在Console.ReadLine上阻止时从单独的线程写入控制台。

话虽如此,它会引起混乱。 在您的情况下,您将清除用户在其行中途输入的内容(通过Console.Clear()),并显着移动光标位置。


编辑:这是一个显示这个的例子:

 namespace ConsoleApplication1 { using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Starting"); ThreadPool.QueueUserWorkItem( cb => { int i = 1; while (true) { Console.WriteLine("Background {0}", i++); Thread.Sleep(1000); } }); Console.WriteLine("Blocking"); Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); } } } 

如果你运行它,你会看到控制台在ReadLine上等待,但后台线程仍然打印。

在循环中使用Console.KeyAvailable。 一旦它返回true,用户就开始输入,所以调用ReadLine()。 但它并没有成为一个非常有吸引力的用户界面。 考虑Windows窗体。

愿此解决方案可以帮助您:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace WaitForExit { class Program { static void Main(string[] args) { new Thread(() => { Console.ReadLine(); Environment.Exit(0); }).Start(); int i = 0; while (true) { Console.Clear(); Console.WriteLine(++i); Thread.Sleep(1000); } } } }