Non-Blocking read from standard I/O in C#

Masoud picture Masoud · Apr 11, 2011 · Viewed 18.2k times · Source

I want a non-blocking read function from console. How do I write that in C#?

Answer

odrm picture odrm · Apr 11, 2011

Richard Dutton has a solution on his blog:

while (true)  
{  
    if (Console.KeyAvailable)  
    {  
        ConsoleKeyInfo key = Console.ReadKey(true);  
        switch (key.Key)  
        {  
            case ConsoleKey.F1:  
                Console.WriteLine("You pressed F1!");  
                break;  
            default:  
                break;  
        }  
    }  
    // Do something more useful  
}