我希望在清除它并显示更多文本之前,在控制台窗口中生成一些文本一段时间。我认为以下代码会这样做,但相反,在计时器到期后,控制台被清除但没有其他文本出现。
这是暂停程序执行直到计时器到期的正确方法吗?
static void Main (string [] args)
{
const int PEEK_TIME = 5;
const int SECOND = 1000;
Timer peekTimer = new Timer (SECOND * PEEK_TIME);
peekTimer.Elapsed += onTimerTick;
peekTimer.AutoReset = false;
peekTimer.Start ();
Console.WriteLine ("Timer started...");
while (peekTimer.Enabled) { }
Console.WriteLine ("Timer done.");
Console.ReadLine ();
}
static void onTimerTick (Object source, System.Timers.ElapsedEventArgs e)
{
Console.Clear ();
}
答案 0 :(得分:2)
这是使用Thread.Sleep函数的codesample。
using System;
using System.Threading;
namespace ConsoleApplication
{
public class Program
{
public static void Main()
{
Console.WriteLine("Timer Start!");
Thread.Sleep(5000);
Console.Clear();
Console.WriteLine("End");
Console.ReadKey();
}
}
}
答案 1 :(得分:0)
在onTimerTick
事件中,如果希望peekTimer.Enabled == false
循环退出,则需要停止计时器(或设置while
):
static void onTimerTick (Object source, System.Timers.ElapsedEventArgs e)
{
Console.Clear ();
peekTimer.Stop();
}
为了做到这一点,你必须在更广的范围内声明计时器,这样你就可以从Main方法和Tick事件处理程序访问它:
namespace ConsoleApplication
{
timer peekTimer;
public class Program
{
在回答您的大问题时,这不是最好的方法。如果你只是坐下来并且在特定的时间内什么都不做,你可能只是让线程睡觉而不是一直旋转:
Console.WriteLine("Waiting 5 seconds...");
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.WriteLine("...Time's up!!");
答案 2 :(得分:0)
你不需要计时器:
static void Main (string [] args)
{
const int PEEK_TIME = 5;
const int SECOND = 1000;
var task = Task.Run(()=>
{
Console.WriteLine ("Work started...");
Thread.Sleep(PEEK_TIME*SECOND);
Console.Clear();
});
task.Wait();
Console.WriteLine ("Work done.");
Console.ReadLine ();
}
答案 3 :(得分:0)
在我的游戏中,我使用这种方法:
public static Timer peekTimer = new Timer (SECOND * PEEK_TIME);
static void Main (string [] args)
{
const int PEEK_TIME = 5;
const int SECOND = 1000;
Console.WriteLine ("Timer started...");
peekTimer.Interval = new TimeSpan(0, 0, 0, 0, SECOND * PEEK_TIME);
peekTimer.Tick += new EventHandler(onTimerTick);
peekTimer.Start();
}
static void onTimerTick (Object source, System.Timers.ElapsedEventArgs e)
{
peekTimer.Stop();
Console.Clear ();
Console.WriteLine ("Timer done.");
Console.ReadLine ();
}