Search code examples
c#.nettimer

DispatcherTimer apply interval and execute immediately


Basically when we apply some interval ie 5 sec we have to wait for it.

Is it possible to apply interval and execute timer immediately and don't wait 5 sec? (I mean the interval time).

Any clue?

Thanks!!

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();
        }
    }

Solution

  • Initially set the interval to zero and then raise it on a subsequent call.

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