I am working with two timers:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace example
{
public partial class Form1 : Form
{
int i = 0;
int j = 0;
public Form1()
{
InitializeComponent();
timer1.Interval = 3000;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
i++;
timer2.Enabled = true;
if (i < 3)
time1(i);
else
timer1.Enabled = false;
}
private void timer2_Tick(object sender, EventArgs e)
{
j++;
timer2.Interval = timer1.Interval / 5;
if (j < 5)
time2(j);
else
timer2.Enabled = false;
}
private void time1(int i)
{
MessageBox.Show(i.ToString(), "First Timer");
}
private void time2(int j)
{
MessageBox.Show(j.ToString(), "SecondTimer");
}
}
}
when running this program it gives an output like this:
firsttimer:1
secondTimer:1
secondTimer:2
secondTimer:3
secondTimer:4
firsttimer:2
in message box.
But when debugging, debug cannot move in that order. After finished the secondtimer:2 it goes back to first timer. But I need to debug in the same order like without breakpoints.
I need for this in another application. Why does this happen?
The problem is, that the underlying timer will continue execution even when you stopped your program with a breakpoint. The
System.Windows.Forms.Timeryou are using will trigger one more event (while aSystem.Timers.Timerwill continue to trigger a lot of events). You can try it on your own:Set a timer to an interval of e.g. 3000ms and set a breakpoint into its eventhandler:
Wait ~3 seconds before you continue your program. The eventhandler will be called immediately again. The next time wait longer (~10 seconds), same result – the eventhandler will be triggered once immediately, then after ~three seconds. Compare the behaviour to
System.Timers.Timer, which will trigger the event in your second testcase more than once.So, depending on your breakpoint (do you set it in
timer1_Tickbeforetimer2.Enabled = true;or after?) and on the time you stop your program before continuing execution you will get different results.Unfortunatly there is nothing you can do. In your special case you could stop all timers before setting a breakpoint, like:
but that would restart the timers and the proportion between the timer1 and timer2 intervals would be wrong.
For more informations about the timers of .net you can read this article.