开发者

How can I update the current line in a C# Windows Console App while waiting for ReadLine?

开发者 https://www.devze.com 2023-01-19 07:38 出处:网络
When building a Windows Console App in C#, is it possible to update lines in the console while waiting for a readline?

When building a Windows Console App in C#, is it possible to update lines in the console while waiting for a readline?

My current code is:

do
{
    Console.Clear();
    Console.WriteLine("RA:     " + scope.RightAscension);
    Console.WriteLine("Dec:    " + s开发者_运维知识库cope.Declination);
    Console.WriteLine("Status: " + scope.Slewing);
    System.Threading.Thread.Sleep(1000);
} while (true);


Yes. You can write to the Console from a separate thread while blocking on Console.ReadLine.

That being said, it's going to cause confusion. In your case, you'll clear out what the user is typing half-way through their line (via Console.Clear()), plus move the cursor position around dramatically.


Edit: Here's an example that shows this:

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

If you run this, you'll see the Console waits on ReadLine, but the background thread still prints.


Use Console.KeyAvailable inside the loop. As soon as it returns true, the user started typing so call ReadLine(). It doesn't make for a very attractive user interface though. Consider Windows Forms.


May this solution helps you:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号