我正在学习套接字消息传递。我在 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' 很长时间。
翻阅古今
相关分类