13

基本上,当我们应用一些间隔,即 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();
        }
    }
4

4 回答 4

20

肯定有更优雅的解决方案,但一个 hacky 方法是在您最初设置间隔后调用 timer_Tick 方法。这比在每个刻度上设置间隔要好。

于 2012-07-03T17:59:10.780 回答
9

最初将间隔设置为零,然后在后续调用中将其提高。

void timer_Tick(object sender, EventArgs e)
{
    ((Timer)sender).Interval = new TimeSpan(0, 0, 5);
    MessageBox.Show("!!!");
}
于 2012-07-03T17:58:21.120 回答
5

可以试试这个:

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
}

另一种方法可能是使用两个事件处理程序(以避免在每次滴答时检查“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
}

然而,更清洁的方式是已经建议的:

timer.Tick += Timer_Tick;
timer.Interval = SOME_INTERVAL;
SomeAction();
timer.Start();

//...

public void Timer_Tick(object sender, EventArgs e)
{
  SomeAction();
}

public void SomeAction(){
  //...
}
于 2014-10-17T10:22:25.090 回答
1

我就是这样解决的:

dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
dispatcherTimer.Start();

DispatcherTimer_Tick(dispatcherTimer, new EventArgs());

为我工作,没有任何问题。

于 2020-03-09T17:27:45.797 回答