C#中标准I / O的非阻塞读取

时间:2011-04-11 11:27:54

标签: c# console-application nonblocking

我想从控制台获得非阻塞读取功能。如何在C#中编写?

2 个答案:

答案 0 :(得分:44)

Richard Duttonhis 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  
} 

答案 1 :(得分:7)

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);
相关问题