日期:2014-05-19  浏览次数:20960 次

Console检测是否有键盘输入
在一个console程序中,有一个循环
while(true)
{
//do   sth
}
如何做到我不按键盘上的键它就一直循环下去,如果我按一个键盘上的任意键,它就停止,跳出循环,就像khbit函数一样。
console.readxx都会阻塞当前线程,直到得到输入,不和我意。
至于另开一个线程,不断检测键盘输入,检测到则停掉该线程,也不太满意。
请指教。

------解决方案--------------------
多线程+ReadKey。。。

------解决方案--------------------
static bool cancled = false;
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(PrintNumber));
thread.Start();
ReadKey();
}

private static void PrintNumber()
{
int i = 0;
while (!cancled)
Console.WriteLine(i++);
}
static void ReadKey()
{
Console.Read();
cancled = true;
}
------解决方案--------------------
while(Console.Read()==-1)
{
//do sth
}