1

I want to use dynamic DispatcherTimer object in my wpf project. I have a timer like below;

DispatcherTimer timer_log = new DispatcherTimer();

I have a list that name is log_durations. The list has durations. And I use this methods to manage timer object.

 int Log = 0,LogDuration=0;

  public void set_timer_log(int interval)
    {
        timer_log.Interval = TimeSpan.FromMilliseconds(interval);
        timer_log.Tick += timer_log_Tick;
        timer_log.IsEnabled = true;
    }

    private void timer_log_Tick(object sender, EventArgs e)
    {
        timer_log.IsEnabled = false;
        try
        {
            if (Log < logs.Length)
            {
                add_package_log(logs[Log]);
                Log++;
                LogDuration++;
                set_timer_log(log_durations[LogDuration]);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Timer Log Tick  Function Error:" + ex.Message);
        }
    }

So when I sum log durations in the list, for example 10 minute. But logs are showing in 30 second. In brief, timer object not works correctly. What is the problem? I couldn't see.

Muammer
  • 374
  • 2
  • 11
  • As a note, the `else` block with `timer_log.Stop()` is redundant, because you have already set `timer_log.IsEnabled = false` before. – Clemens Dec 04 '19 at 13:32
  • 1
    `set_timer_log` method is called multiple times and adds event handler to Tick event multiple times. – ASh Dec 04 '19 at 13:32
  • As Ash has mentioned, move `timer_log.Tick += timer_log_Tick;` out of the `set_timer_log` method, and call it only once after `timer_log` creation. – Clemens Dec 04 '19 at 13:38
  • The problem was solved with the contributions of @ASh and Clemens. Thanks a lot! – Muammer Dec 04 '19 at 13:46

1 Answers1

2

This code works clearly.

 DispatcherTimer timer_log = new DispatcherTimer();
 timer_log.Tick += timer_log_Tick;
 int Log = 0,LogDuration=0;

 public void set_timer_log(int interval)
   {
    timer_log.Interval = TimeSpan.FromMilliseconds(interval);
    timer_log.IsEnabled = true;
   }

private void timer_log_Tick(object sender, EventArgs e)
   {
     timer_log.IsEnabled = false;
    try
      {
        if (Log < logs.Length)
           {
            add_package_log(logs[Log]);
            Log++;
            LogDuration++;
            set_timer_log(log_durations[LogDuration]);
           }
      }
    catch (Exception ex)
    {
        MessageBox.Show("Timer Log Tick  Function Error:" + ex.Message);
    }
}
Muammer
  • 374
  • 2
  • 11