【问题标题】:c# - can i run code while requesting ReadLine from the user?c# - 我可以在向用户请求 ReadLine 时运行代码吗?
【发布时间】:2021-05-07 15:29:21
【问题描述】:

我有一个在后台运行的循环。同时我需要程序来注册用户的输入,并让代码在任何输入发生时做出反应。我可以这样做吗?

所以从像这样的 sn-p-

string input = ""; 
while(true)
{
  Console.WriteLine(input);
}
input = PermanentReadLine();

我希望它在我向 ReadLine 写入任何内容时更改它写入屏幕的内容

【问题讨论】:

标签: c#


【解决方案1】:

您可以通过让一个任务读取输入和一个单独的任务来处理它来实现这一点。这是使用Channels 的实现:

async Task Main()
{
    var channel = Channel.CreateUnbounded<string>();
    var worker = Task.Run(async () =>
    {
        while (await channel.Reader.WaitToReadAsync())
            while (channel.Reader.TryRead(out var input))
                Console.WriteLine(input);
    });
    
    while (true)
    {
        var input = Console.ReadLine();
        if (input.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
        {
            channel.Writer.Complete();
            break;
        }
        channel.Writer.TryWrite(input);
    }
}

当用户键入“exit”时,此示例终止。

【讨论】:

    【解决方案2】:
    Task.Run(() => {
        while(true)
        {
           string input = Console.ReadLine();
    
           // Do something with the input. Maybe switch or if/else statement?
        }
    });
    

    这仍将允许程序的其余部分继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 2016-09-22
      • 2014-05-04
      相关资源
      最近更新 更多