C#控制台应用程序-如何始终从控制台读取输入? [英] C# Console Application - How do I always read input from the console?
本文介绍了C#控制台应用程序-如何始终从控制台读取输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在编写一个使用大量多线程的控制台应用程序.我希望始终允许用户在控制台中输入内容,但是线程会定期向控制台输出内容,但我希望用户始终能够将内容输入到控制台中并由我来处理输入
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?
感谢进阶!
这是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...");
}
}
}
这篇关于C#控制台应用程序-如何始终从控制台读取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文