我正在學習套接字消息傳遞。我在 while 循環中中斷了 Console.ReadKey() 并且很多調用最終都未完成。我正在嘗試找到一種方法來刪除不完整的調用,而無需用戶將其全部輸入。我見過while(Console.KeyAvailable){Console.ReadKey(true);}但我有相反的問題,太多的電話沒有足夠的擊鍵。如何向 Console.ReadLine() 添加超時? 這個問題讓我到了現在的位置,但它并沒有解決我當前的問題。using System;using System.Threading;class Program{ static void Main(string[] args) { DontLockOnCharGet bug = new DontLockOnCharGet(); bug.Setup(); }}public class DontLockOnCharGet{ public void Setup() { while (true) { DontLockCharGet(); } } public void DontLockCharGet() { while (true) { // used to interrupt the Console.ReadKey() function AutoResetEvent getInput = new AutoResetEvent(false); AutoResetEvent gotInput = new AutoResetEvent(false); // Console.ReadKey() assigns to input char input = ' '; //Lambda used to get rid of extra class Thread tom = new Thread(() => { getInput.WaitOne(); // Waits for getInput.Set() //The problem with this is the read keys stacking up // causing the need for a lot of keystrokes input = Console.ReadKey().KeyChar; gotInput.Set(); }) { IsBackground = true }; // Starts Lambda function tom.Start(); // Allows thread to pass WaitOne() in Lambda getInput.Set(); // Gives some milliseconds for before stopping Lambda exe gotInput.WaitOne(2000); if (input == 'S' || input == 's') { break; } // thinking I would put the solution here //... } //Do stuff if input is s || S Console.Write("end: "); }}我希望能夠按 's' || 'S' 然后輸入一條消息,但根據我等待的時間長短,我可能需要按住 's' 很長時間。
1 回答

翻閱古今
TA貢獻1780條經驗 獲得超5個贊
問題出在new Thread(()=> { ... });This is creating a new function 而不僅僅是新函數調用。正在創建的函數應該像這樣移動到一個單獨的函數中
private void ReadKey(){
// Waits for getInput.Set()
getInput.WaitOne();
//The problem with this is the read keys stacking up
// causing the need for a lot of keystrokes
input = Console.ReadKey().KeyChar;
gotInput.Set();
}
在班級里面。
做這些
AutoResetEvent getInput, gotInput;
char input;
類變量并在內部初始化它們Setup(){...}
最后Thread tom = new Thread(ReadKey);在當前正在制作新功能的地方調用。
注意:此答案不適用于最佳實踐,但會得到一個原型來工作。
- 1 回答
- 0 關注
- 123 瀏覽
添加回答
舉報
0/150
提交
取消