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

时间:2014-04-06 20:12:54

标签: c# multithreading input console-application

我目前正在编写一个使用大量多线程的控制台应用程序。我希望能够始终允许用户在控制台中输入内容,但是,从线程将定期输出到控制台,但我希望用户始终能够将内容输入控制台并让我处理输入

我将如何实现这一目标?我在网上找不到任何关于它的信息?

先谢谢!

这是针对c#btw!

1 个答案:

答案 0 :(得分: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...");
    }
  }
}