C#Console.ReadKey 1个字符滞后?

C S*_*ith 0 c# console.readkey

我正在尝试使用Console.ReadKey()函数来拦截用户的击键并重建他们在屏幕上键入的内容(因为我需要经常清除屏幕,经常移动光标,这似乎比如最全面的方法,确保他们输入的内容不会消失或出现在整个屏幕上的随机点.

我的问题是:在做类似的事情时,有没有其他人经历过1个字符"滞后",因为缺乏更好的术语?说我想输入单词"This".当我按"T"时,无论我等多久都没有出现.当我按"h"时,出现"T"."我","h"出现.直到我按下另一个键,即使该键是空格键,我输入的字母也不会出现.有没有人对我做错了什么有任何建议?我确定它与我如何使用Console.Readkey有关,我只是看不出有什么替代方法可行.我在下面附上了一个简单的小例子.

谢谢!

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    namespace ConsoleApplication2

{
    class Program
    {

        private static string userInput = "";
        static ConsoleKeyInfo inf;
        static StringBuilder input = new StringBuilder();

        static void Main(string[] args)
        {
            Thread tickThread = new Thread(new ThreadStart(DrawScreen));
            Thread userThread = new Thread(new ThreadStart(UserEventHandler));
            tickThread.Start();
            Thread.Sleep(1);
            userThread.Start();
            Thread.Sleep(20000);
            tickThread.Abort();
            userThread.Abort();
        }


        private static void DrawScreen()
        {
            while (true)
            {
                Console.Clear();
                Console.SetCursorPosition(0, 0);
                Console.Write("> " + userInput);
                Thread.Sleep(300);
            }
        }


        private static void UserEventHandler()
        {
            inf = Console.ReadKey(true);

            while (true)
            {
                if (inf.Key != ConsoleKey.Enter)
                    input.Append(inf.KeyChar);
                else
                {
                    input = new StringBuilder();
                    userInput = "";
                }

                inf = Console.ReadKey(true);

                userInput = input.ToString();

            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

bar*_*t s 5

这是因为你有2次 Console.ReadKey()

如果您将代码更改为此

    private static void UserEventHandler()
    {
        while (true)
        {
            inf = Console.ReadKey(true);
            if (inf.Key != ConsoleKey.Enter)
                input.Append(inf.KeyChar);
            else
            {
                input = new StringBuilder();
                userInput = "";
            }
            userInput = input.ToString();
        }
    }
Run Code Online (Sandbox Code Playgroud)

它没有滞后.第二个Console.ReadKey()是阻止你的代码.我没有检查你是否需要true读取密钥的参数,这是你找到的