C# Console Application - How do I always read inpu

2019-06-14 16:50发布

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条回答
放荡不羁爱自由
2楼-- · 2019-06-14 17:24
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...");
    }
  }
}
查看更多
登录 后发表回答