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

確かにもっと洗練された解決策がありますが、最初に間隔を設定した後に 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
}

もう 1 つの方法は、2 つのイベント ハンドラーを使用することです (すべてのティックで "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 に答える