基本上当我们应用一些间隔即5秒时我们必须等待它.
是否可以立即应用间隔和执行定时器,不等待5秒?(我的意思是间隔时间).
任何线索?
谢谢!!
public partial class MainWindow : Window
{
DispatcherTimer timer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
timer.Tick += new EventHandler(timer_Tick);
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("!!!");
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
最初将间隔设置为零,然后在后续调用中将其提高.
void timer_Tick(object sender, EventArgs e)
{
((Timer)sender).Interval = new TimeSpan(0, 0, 5);
MessageBox.Show("!!!");
}
Run Code Online (Sandbox Code Playgroud)
可以试试这个:
timer.Tick += Timer_Tick;
timer.Interval = 0;
timer.Start();
//...
public void Timer_Tick(object sender, EventArgs e)
{
if (timer.Interval == 0) {
timer.Stop();
timer.Interval = SOME_INTERVAL;
timer.Start();
return;
}
//your timer action code here
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用两个事件处理程序(以避免在每个滴答声中检查“if”):
timer.Tick += Timer_TickInit;
timer.Interval = 0;
timer.Start();
//...
public void Timer_TickInit(object sender, EventArgs e)
{
timer.Stop();
timer.Interval = SOME_INTERVAL;
timer.Tick += Timer_Tick();
timer.Start();
}
public void Timer_Tick(object sender, EventArgs e)
{
//your timer action code here
}
Run Code Online (Sandbox Code Playgroud)
然而,更清洁的方法是已经建议的:
timer.Tick += Timer_Tick;
timer.Interval = SOME_INTERVAL;
SomeAction();
timer.Start();
//...
public void Timer_Tick(object sender, EventArgs e)
{
SomeAction();
}
public void SomeAction(){
//...
}
Run Code Online (Sandbox Code Playgroud)