問題描述
使用控制臺(tái)編寫服務(wù)器程序,服務(wù)器和客戶端的通信使用異步通信處理,另外控制臺(tái)可以通過用戶輸入命令查看響應(yīng)信息,即控制臺(tái)需要滿足一邊通信一邊可以接收用戶輸入,但是問題出現(xiàn)了,控制臺(tái)在等待用戶輸入的時(shí)候(偶爾)會(huì)處于阻塞狀態(tài),此時(shí)服務(wù)器無法接收到客戶端消息。
解決方案
使用Console.KeyAvailable屬性解決Console.ReadKey() 阻塞問題,以下是項(xiàng)目中的代碼
ConsoleKeyInfo cki = new ConsoleKeyInfo();
do
{
if (Console.KeyAvailable)
{
cki = Console.ReadKey(false);
Console.WriteLine("You pressed the '{0}' key.", cki.Key);
switch (cki.Key)
{
case ConsoleKey.C:
//do something
break;
case ConsoleKey.E:
//do something
break;
case ConsoleKey.Q:
//do something
break;
default:
break;
}
}
}
while (cki.Key != ConsoleKey.Q);
知識(shí)擴(kuò)展
在控制臺(tái)程序中,幾種讀取輸入方法的比較
| 方法 | Read() | ReadKey() | ReadKey(Boolean) | ReadLine() |
|---|---|---|---|---|
| 功能 | 從標(biāo)準(zhǔn)輸入流讀取下一個(gè)字符 | 獲取用戶按下的下一個(gè)字符或功能鍵。 按下的鍵顯示在控制臺(tái)窗口中。 | 獲取用戶按下的下一個(gè)字符或功能鍵。 按下的鍵可以選擇顯示在控制臺(tái)窗口中。True:不顯示在控制臺(tái),F(xiàn)alse:顯示在控制臺(tái) | 從標(biāo)準(zhǔn)輸入流讀取下一行字符 |
| 返回值 | 輸入流中的下一個(gè)字符;如果當(dāng)前沒有更多的字符可供讀取,則為負(fù)一 (-1) | 一個(gè) ConsoleKeyInfo對(duì)象,描述 ConsoleKey 常數(shù)和對(duì)應(yīng)于按下的控制臺(tái)鍵的 Unicode 字符(如果存在這樣的字符) | 同上 | 輸入流中的下一行字符;如果沒有更多的可用行,則為 空引用(在 Visual Basic 中為 Nothing)。 |
| 備注 | 在鍵入輸入字符時(shí),Read 方法會(huì)阻止其返回;該方法在您按 Enter 鍵時(shí)終止。使用 ReadLine 方法或使用 KeyAvailable屬性和 ReadKey方法比使用 Read 方法更可取 | ConsoleKeyInfo 類型不應(yīng)由用戶創(chuàng)建。實(shí)際上,它作為調(diào)用 Console.ReadKey方法的響應(yīng)返回給用戶 | 同上 | 行被定義為后跟回車符(十六進(jìn)制 0x000d)、換行符(十六進(jìn)制 0x000a)或[Environment.NewLine 屬性值的字符序列。返回的字符串不包含終止字符。 |
使用Console.KeyAvailable屬性解決阻塞
屬性值
如果按鍵操作可用,則為 true;否則為 false。
備注
屬性值會(huì)立即返回,也就是說,KeyAvailable 屬性不會(huì)為等待按鍵操作可用而阻止輸入。
請(qǐng)只將 KeyAvailable 屬性與ReadKey 方法結(jié)合使用,而不是與Read 或 ReadLine 方法結(jié)合使用。
示例
// This example demonstrates the Console.KeyAvailable property.
using System;
using System.Threading;
class Sample
{
public static void Main()
{
ConsoleKeyInfo cki = new ConsoleKeyInfo();
do {
Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
// Your code could perform some useful task in the following loop. However,
// for the sake of this example we'll merely pause for a quarter second.
while (Console.KeyAvailable == false)
Thread.Sleep(250); // Loop until input is entered.
cki = Console.ReadKey(true);
Console.WriteLine("You pressed the '{0}' key.", cki.Key);
} while(cki.Key != ConsoleKey.X);
}
}
/*
This example produces results similar to the following text:
Press a key to display; press the 'x' key to quit.
You pressed the 'H' key.
Press a key to display; press the 'x' key to quit.
You pressed the 'E' key.
Press a key to display; press the 'x' key to quit.
You pressed the 'PageUp' key.
Press a key to display; press the 'x' key to quit.
You pressed the 'DownArrow' key.
Press a key to display; press the 'x' key to quit.
You pressed the 'X' key.
*/