我已经构建了一个简单的控制台应用程序,并且我需要为用户提供一个特定的时间来输入keychar。
我应该用这个吗?
System.Threading.Thread.Sleep(1000);对于那些不理解的人,我需要程序在x秒之后跳过Console.ReadKey().KeyChar;。
这个是可能的吗?
发布于 2013-12-17 15:39:22
我会这样做:
DateTime beginWait = DateTime.Now;
while (!Console.KeyAvailable && DateTime.Now.Subtract(beginWait).TotalSeconds < 5)
Thread.Sleep(250);
if (!Console.KeyAvailable)
Console.WriteLine("You didn't press anything!");
else
Console.WriteLine("You pressed: {0}", Console.ReadKey().KeyChar);发布于 2013-12-17 15:28:39
问题:如果您使用Thread.Sleep()等待1秒,它会在给定的时间段内挂起主线程。
解决方案:您可以使用System.Timers.Timer等待给定的时间。
试试这个:
System.Timers.Timer timer1 = new System.Timers.Timer();
timer1.Interval=1000;//one second
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
timer1.Start();
char ch;
private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
ch=Console.ReadKey().KeyChar;
//stop the timer whenever needed
//timer1.Stop();
}https://stackoverflow.com/questions/20628279
复制相似问题