2012-07-03 10 views
8

基本的には5秒間隔、つまり5秒間を適用すると、それを待たなければなりません。DispatcherTimerは間隔を適用してすぐに実行します

インターバルを適用してすぐにタイマーを実行し、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(); 
     } 
    } 
+2

すぐに何かを起こしたい場合は、ただちに実行してみませんか? – dlev

+1

@dlevしかし、私はよりエレガントな方法を見たいと思っています... –

+0

私はメソッドを直接呼び出すことについて何が面白いのか分かりません。あなたはおそらく両方の場所で呼び出される新しいメソッドを作成すべきですが、アイデアは同じです:何かが今起きたければ、それをやり直してください! – dlev

答えて

7

最初に間隔をゼロに設定し、その後の呼び出しでそれを上げます。

void timer_Tick(object sender, EventArgs e) 
{ 
    ((Timer)sender).Interval = new TimeSpan(0, 0, 5); 
    MessageBox.Show("!!!"); 
} 
+0

ジンのソリューションはよりクリーンです。 –

13

間違いなくより洗練された解決策がありますが、最初に間隔を設定した後は、timer_Tickメソッドを呼び出すだけです。それは、すべてのダニで間隔を設定するよりも良いでしょう。

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 = 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 
} 

別の方法(ティックごとに「場合」をチェック避けるために)2つのイベントハンドラを使用することができます

2

することは、これは試みることができます既に提案されています:

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

//... 

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

public void SomeAction(){ 
    //... 
} 
関連する問題