我试图做一个preSS Q退出的事,在控制台窗口。我不喜欢我目前的执行情况。有没有一种方法,我可以异步或使用一个回调来从控制台按键?
I am trying to do a press Q to quit thing in the console window. I dont like my current implementation. Is there a way i can async or use a callback to get keys from the console?
您可以致电 Console.ReadKey()
从另一个线程,所以它不会阻止你的主线程。 (您可以使用.NET 4 工作
或旧发
启动新的线程。)
You can call Console.ReadKey()
from another thread, so that it doesn't block your main thread. (You can use the .Net 4 Task
or the old Thread
to start the new thread.)
class Program
{
static volatile bool exit = false;
static void Main()
{
Task.Factory.StartNew(() =>
{
while (Console.ReadKey().Key != ConsoleKey.Q) ;
exit = true;
});
while (!exit)
{
// Do stuff
}
}
}