假设我的控制台程序执行多个冗长的任务。在这些任务之间,我希望它暂停 - 几秒钟或直到按下任何键。(以先到者为准。)
这些标准很容易自行检查,但是当我尝试将它们组合起来时它们拒绝相处:要么计时机制在 ReadKey 启动之前暂停几秒钟,要么Readkey 完全阻塞线程直到满足。我怎样才能同时满足这两个条件?
在 C# 4.0 中执行此操作的一种方法:
Task.Factory.StartNew(() => Console.ReadKey()).Wait(TimeSpan.FromSeconds(5.0));
一种方法是根本没有计时器。创建一个循环,使线程休眠 25 毫秒,然后检查是否已通过Console.KeyAvailable(非阻塞)按下某个键,或者直到DateTime.Now()
循环开始的时间超过暂停。
从ikh的回答延伸我想用我的倒计时
var original = DateTime.Now;
var newTime = original;
var waitTime = 10;
var remainingWaitTime = waitTime;
var lastWaitTime = waitTime.ToString();
var keyRead = false;
Console.Write("Waiting for key press or expiring in " + waitTime);
do
{
keyRead = Console.KeyAvailable;
if (!keyRead)
{
newTime = DateTime.Now;
remainingWaitTime = waitTime - (int) (newTime - original).TotalSeconds;
var newWaitTime = remainingWaitTime.ToString();
if (newWaitTime != lastWaitTime)
{
var backSpaces = new string('\b', lastWaitTime.Length);
var spaces = new string(' ', lastWaitTime.Length);
Console.Write(backSpaces + spaces + backSpaces);
lastWaitTime = newWaitTime;
Console.Write(lastWaitTime);
Thread.Sleep(25);
}
}
} while (remainingWaitTime > 0 && !keyRead);
启动两个线程。一个监听按键,另一个等待一段时间。让主线程等待,除非任何一个完成。然后继续并忽略其他线程响应。:)
像这样的东西?
bool IsPaused;
bool IsKeyPaused;
void Pause(){}
void UnPause(){}
void KeyDown(){
if(!IsPaused)
{
IsPaused = true;
IsKeyPaused = true;
Pause();
}
}
void KeyUp(){
if(IsKeyPaused)
{
IsPaused = false;
IsKeyPaused = false;
UnPause();
}
}
void TimerPause(){
if(!IsPaused)
{
IsPaused = true;
Pause();
}
}
void TimerEnd(){
UnPause();
}