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

2019-01-15 05:54发布

问题:

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

回答1:

var buf=new byte[2048];
var inputStream=Console.OpenStandardInput(); //dispose me when you're done
inputStream.BeginRead(buf,0,buf.Length,ar=>{
    int amtRead=inputStream.EndRead(ar);
    //buf has what you need. You'll need to decode it though
},null);


回答2:

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  
}