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?
+4
A:
You can call Console.ReadKey() from another thread, so that it doesn't block your main thread. (You can use the C# 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
}
}
}
svick
2010-08-01 14:49:19
Thats actially what i am doing (well, the readkey part on a dif thread). This task factory looks cool. The problem with my code right now is .ReadKey seems to not return unless i bring the window to focus. Hence why i dont like my solution. When the main thread ends the other thread is still locked up. Your solution looks cool, maybe task threads will die when the main does. In that case this should work however ATM This is a 3.5 only app.
acidzombie24
2010-08-01 15:41:31
Avoid the thread by using Console.KeyAvailable.
Hans Passant
2010-08-01 16:24:06
If you want the `Thread` to stop when the main thread finishes, just set `Thread.IsBackground` to `true`.
svick
2010-08-01 16:26:34
Both the code above and the IsBackground solve my problem. +1
acidzombie24
2010-08-01 17:46:56