Ok it seems several people are looking for timer programs. This tutorial will show you how to use Threading and Invoke to update your timer on your program.
Create a new Windows application and add the this using statement
csharp
using System.Threading;
on your form you will need to add a label and call it lblTimerDisplay this will display your timer.
next add a button to start the timer and another button to stop it.
you will need to add a timer delegate and a variable for your delegate here are mine
csharp
private delegate void Timer(string time);
Timer timer1;
now declare three variables for the time as a double and one as a string also a boolean for the timer
csharp
private double time = 0.0;
private bool timerStarted = false;
private string returnTime = string.Empty;
now create a method to update your label with your string value time.
csharp
private void UpdateTimer(string time)
{
this.lblTimerDisplay.Text = time;
}
ok now create a property that will return a string value of your timer
csharp
public string Counter
{
get{return returnTime;}
}
now create a method that will update your timer in a .01 increment and will invoke your label control.
csharp
private void DisplayTimer()
{
do
{
time += 0.01;
time = Convert.ToDouble(time.ToString("0.00"));
returnTime = Convert.ToString(time);
this.lblTimerDisplay.Invoke(timer1, new object[] { Counter });
} while (timerStarted);
}
now you will need to initialize your timer1 delegate to your UpdateTimer method in your constructor
scharp
timer1 = new Timer(UpdateTimer);
now on your form double click your start button. In the button click event you will need to set your thread to start the DisplayTimer method you will need to set your timerStarted variable to true and start your thread
csharp
private void btnStart_Click(object sender, EventArgs e)
{
System.Threading.Thread startTimer = new System.Threading.Thread(
new System.Threading.ThreadStart(DisplayTimer));
timerStarted = true;
startTimer.Start();
}
now all you have to do is set timerStarted to false in your stop button click event to stop the timer.
csharp
private void btnStopTimer_Click(object sender, EventArgs e)
{
timerStarted = false;
}