C# Console Application - How do I always read inpu

2019-06-14 17:25发布

问题:

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!

回答1:

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...");
    }
  }
}