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

如何让控制台程序模拟用户输入自交互,规避Console.ReadLine()阻塞

解决方案

可以通过重定向Console.In输入流的方式实现,几乎不需要改动原有核心代码,具体步骤如下:

  • 构建包含模拟输入内容的字符串流,每个输入后添加换行符(匹配Console.ReadLine()读取到换行结束的逻辑)
  • 将该流赋值给Console.In,让Console.ReadLine()从模拟流读取内容,而非等待手动输入
  • 配合等待方法实现输入间隔

修改后的代码示例:

using System;
using System.IO;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        // 构造模拟输入,每个输入后加换行
        var simulatedInput = "1\n2\n3\n";
        // 重定向控制台输入流
        Console.SetIn(new StringReader(simulatedInput));

        // 原有核心代码几乎无改动
        string userInput = Console.ReadLine();
        Console.WriteLine("hello");
        Console.WriteLine("user wrote to me: " + userInput);
        
        Thread.Sleep(1000);
        
        userInput = Console.ReadLine();
        Console.WriteLine("hello");
        Console.WriteLine("user wrote to me: " + userInput);
        
        Thread.Sleep(1000);
        
        userInput = Console.ReadLine();
        Console.WriteLine("hello");
        Console.WriteLine("user wrote to me: " + userInput);
    }
}

如果项目支持异步,也可以用await Task.Delay(1000)替代Thread.Sleep(1000),仅需将Main方法改为异步即可。这种方式通过输入流重定向欺骗Console.ReadLine(),完全满足少改动代码的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:03:25