You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在输入时实时输出字符串长度?打字竞速程序开发优化

打字竞速程序实时输入长度跟踪解决方案

问题说明

我正在开发一款小型打字竞速程序,用户需输入上方显示的文本。当用户输入达到字符限制时,程序需告知用户用时。目前已实现该功能,但需用户输入完成后按回车触发;希望程序能实时跟踪输入文本的长度,我认为这涉及线程管理。

现有代码

var words = "the you that it he she why when is";
TimeOnly timeNow1 = new TimeOnly();
            
while (words2.Length !< numwords)
{
  timeNow1 = TimeOnly.FromDateTime(DateTime.Now);
  Console.WriteLine(words2.Length);
  words2 = Console.ReadLine();
}
var timeNow2 = TimeOnly.FromDateTime(DateTime.Now);
var time = (timeNow2 - timeNow1);
            
Console.WriteLine(time.Seconds);
Console.WriteLine(words2.Length);

解决方案

原代码里的Console.ReadLine()会阻塞线程直到用户按下回车,所以要实现实时跟踪输入长度,必须用多线程拆分任务:一个线程负责监听每一次按键输入,另一个线程负责计时和长度校验。

核心思路

  1. 主线程:负责展示目标文本、启动计时、实时检查输入长度,当长度达标时立即停止计时并输出结果。
  2. 输入监听线程:独立读取用户的每一个按键,维护当前输入的字符串,无需等待回车触发。

优化后代码

using System;
using System.Threading;

class TypingRace
{
    static string currentInput = string.Empty;
    static bool isRunning = true;

    static void Main()
    {
        string targetText = "the you that it he she why when is";
        int targetLength = targetText.Length;
        Console.WriteLine("请输入以下文本:\n" + targetText);

        // 启动输入监听线程
        Thread inputThread = new Thread(ListenForInput);
        inputThread.Start();

        // 开始计时
        DateTime startTime = DateTime.Now;

        // 循环监控输入长度,达标则终止程序
        while (isRunning)
        {
            if (currentInput.Length >= targetLength)
            {
                isRunning = false;
                TimeSpan elapsedTime = DateTime.Now - startTime;
                Console.WriteLine($"\n输入完成!用时:{elapsedTime.TotalSeconds:F2} 秒");
                Console.WriteLine($"输入长度:{currentInput.Length}");
                break;
            }
            Thread.Sleep(100); // 降低循环CPU占用率
        }

        inputThread.Join();
    }

    static void ListenForInput()
    {
        while (isRunning)
        {
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey(true);
                // 处理退格键,删除最后一个字符并更新控制台显示
                if (key.Key == ConsoleKey.Backspace && currentInput.Length > 0)
                {
                    currentInput = currentInput.Substring(0, currentInput.Length - 1);
                    Console.SetCursorPosition(currentInput.Length, Console.CursorTop);
                    Console.Write(" ");
                    Console.SetCursorPosition(currentInput.Length, Console.CursorTop);
                }
                // 处理可打印字符,追加到输入字符串并显示
                else if (!char.IsControl(key.KeyChar))
                {
                    currentInput += key.KeyChar;
                    Console.Write(key.KeyChar);
                }
            }
            Thread.Sleep(10);
        }
    }
}

代码说明

  • 输入监听逻辑:通过Console.KeyAvailable检测是否有按键输入,Console.ReadKey(true)读取按键但不自动输出,方便自定义退格和输入显示的逻辑。
  • 线程同步:用isRunning布尔变量控制两个线程的生命周期,避免线程泄漏。
  • 性能优化:主线程和输入线程分别加入短时间休眠,减少不必要的CPU资源占用。

内容的提问来源于stack exchange,提问作者user20654632

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:45:30