The variation in timing
may be due to garbage collection happening; read the commented code in the 'Main method here: [
^]. Use of the 'GC.KeepAlive(YourTimerName)
may have an impact on this variation.
In any case you can simplify your code by setting the 'Synchronization object-property of the Timer. Try this:
using System;
using System.Timers;
using System.Windows.Forms;
namespace YourNameSpace
{
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private int iCounter = 6000;
private int iInterval = 10;
private System.Timers.Timer t1 = new System.Timers.Timer();
private void Form1_Load(object sender, EventArgs e)
{
t1.Interval = iInterval;
t1.Elapsed += t1_Elapsed;
t1.SynchronizingObject = this;
lblTimer.Text = iCounter.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
GC.KeepAlive(t1);
t1.Enabled = true;
}
private void t1_Elapsed(object sender, ElapsedEventArgs e)
{
lblTimer.Text = (iCounter -= iInterval).ToString();
if (iCounter <= 0)
{
t1.Stop();
lblTimer.Text += " : Stopped";
}
}
}
}
I suggest you experiment with running the code with, and without, the call to 'GC.KeepAlive(t1) and see if you observe any run-time differences.