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

时间:2010-10-11 15:34:33

标签: c# console readline

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

是。您可以在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上等待,但后台线程仍在打印。

答案 2 :(得分:0)

这个解决方案可以帮助你:

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