简体   繁体   English

C#控制台应用程序-如何始终从控制台读取输入?

[英]C# Console Application - How do I always read input from the console?

I am currently writing a console application which uses a lot of multithreading. 我目前正在编写一个使用大量多线程的控制台应用程序。 I want to be able to always allow the user to enter something into the console however, there will be regular output to the console from the threads but I want users to be always able to enter things into the console and for me to handle the input. 我希望始终允许用户在控制台中输入内容,但是线程会定期向控制台输出内容,但是我希望用户始终能够将内容输入到控制台中并由我来处理输入。

How would I achieve this? 我将如何实现? I've found nothing online about it? 我在网上找不到任何东西吗?

Thanks in advanced! 提前致谢!

This is for c# btw! 这是c#btw!

class Program
{
  static void Main(string[] args)
  {
    // cancellation by keyboard string
    CancellationTokenSource cts = new CancellationTokenSource();

    // thread that listens for keyboard input
    var kbTask = Task.Run(() =>
    {
      while(true)
      {
        string userInput = Console.ReadLine();
        if(userInput == "c")
        {
          cts.Cancel();
          break;
        }
        else
        {
          // handle input
          Console.WriteLine("Executing user command {0}...", userInput);
        }
      }
    });

    // thread that performs main work
    Task.Run(() => DoWork(), cts.Token);

    Console.WriteLine("Type commands followed by 'ENTER'");
    Console.WriteLine("Enter 'C' to end program.");
    Console.WriteLine();

    // keep Console running until cancellation token is invoked
    kbTask.Wait();
  }

  static void DoWork()
  {
    while(true)
    {
      Thread.Sleep(3000);
      Console.WriteLine("Doing work...");
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM