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

C# 控制台应用如何实现指定时长等待按键输入,无输入则继续执行?

C# 控制台实现限时按键输入的方案

原生Console.ReadKey()没有直接提供超时参数,你可以通过以下两种通用方案实现需求:


方案1:兼容全版本.NET的实现

配合Console.KeyAvailable属性做轮询检测,适用于.NET Framework、.NET Core所有版本:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine("请在100毫秒内按任意键...");
        const int timeoutMs = 100;
        bool hasInput = false;
        ConsoleKeyInfo inputKey = default;

        // 每10ms检测一次按键,直到超时
        for (int i = 0; i < timeoutMs / 10; i++)
        {
            if (Console.KeyAvailable)
            {
                // intercept设为true表示不把按键回显到控制台,需要回显可改为false
                inputKey = Console.ReadKey(intercept: true);
                hasInput = true;
                break;
            }
            Thread.Sleep(10);
        }

        if (hasInput)
        {
            Console.WriteLine($"检测到按键:{inputKey.Key}");
        }
        else
        {
            Console.WriteLine("100毫秒内无按键,继续执行后续逻辑");
        }

        // 你的后续业务代码
    }
}

方案2:.NET Core 3.0+ / .NET 5+ 更精准的实现

高版本.NET的Console.ReadKey新增了支持取消令牌的重载,可以配合超时取消令牌实现无轮询的精准等待:

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Console.WriteLine("请在100毫秒内按任意键...");
        using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
        bool hasInput = false;
        ConsoleKeyInfo inputKey = default;

        try
        {
            inputKey = Console.ReadKey(intercept: true, cts.Token);
            hasInput = true;
        }
        catch (OperationCanceledException)
        {
            // 超时触发取消,无需额外处理异常
        }

        if (hasInput)
        {
            Console.WriteLine($"检测到按键:{inputKey.Key}");
        }
        else
        {
            Console.WriteLine("100毫秒内无按键,继续执行后续逻辑");
        }

        // 你的后续业务代码
    }
}

注意事项

  • 调用Console.ReadKey是为了消费控制台输入缓冲区的按键数据,如果只检测Console.KeyAvailable不读取按键,该属性会一直返回true
  • 如果需要同时监听特定按键,读取到ConsoleKeyInfo后判断Key属性即可,比如if (inputKey.Key == ConsoleKey.Escape)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:54:00