It is not much code that you posted, but I would give it a try.
I don't see in your code any bool
variable.
You probably should have one where you would save the current state.
since you write the value into the TextBox
you could start the timer that MMbach suggested right after the line:
sqlserver_status.Text = "Active";
// start timer here
whenever further in you code this status changes, you would stop the timer and check the elapsed time.
You could also use the StopWatch class for that.
It has a property called Elapsed
which :
Gets the total elapsed time measured by the current instance.
If you need to run it in the background I would advise to go for the Timer
.
Below is a small Demo realised with a System.Diagnostics.Stopwatch
.
There are many more realisation to this problem. It always depends on the structure of your program which realisation is better or worse.
This is a small Console application where you decide when to change the State
Variable. It will monitor your decision process.
public class TimeDemo
{
// Property to catch the timespan
public TimeSpan TimeOfState { get; set; }
// Full Property for the state
private bool state;
public bool State
{
get { return state; }
set
{
// whenever a new state value is set start measuring
state = value;
this.TimeOfState = StopTime();
}
}
// Use this to stop the time
public System.Diagnostics.Stopwatch StopWatch { get; set; }
public TimeDemo()
{
this.StopWatch = new System.Diagnostics.Stopwatch();
}
//Method to measure the elapsed time
public TimeSpan StopTime()
{
TimeSpan t = new TimeSpan(0, 0, 0);
if (this.StopWatch.IsRunning)
{
this.StopWatch.Stop();
t = this.StopWatch.Elapsed;
this.StopWatch.Restart();
return t;
}
else
{
this.StopWatch.Start();
return t;
}
}
public void Demo()
{
Console.WriteLine("Please press Enter whenever you want..");
Console.ReadKey();
this.State = !this.State;
Console.WriteLine("Elapsed Time: " + TimeOfState.ToString());
Console.WriteLine("Please press Enter whenever you want..");
Console.ReadKey();
this.State = !this.State;
Console.WriteLine("Elapsed Time: " + TimeOfState.ToString());
Console.WriteLine("Please press Enter whenever you want..");
Console.ReadKey();
this.State = !this.State;
Console.WriteLine("Elapsed Time: " + TimeOfState.ToString());
}
}
May be you can adjust it according to your case.