using Timer to know the age of an object
I am writing a class named Food. I considered a field “int cookingTime” to see how long each instance of this class has been existed. I assumed I should use the Timer class. I wrote the following piece of code but it did not work. I am not sure if my approach is correct . I really appreciate any help.
Class Food
{
private System.Timers.Timer timerClock = new System.Timers.Timer();
static int cookingTime = 0;
public Food开发者_如何学Go()
{
this.timerClock.Elapsed += new System.Timers.ElapsedEventHandler(process);
this.timerClock.Interval = 1000;
this.timerClock.Enabled = true;
}
static void process(Object myObject, EventArgs myEventArgs)
{
cookingTime += 1;
}
}
How about saving the timestamp of the creation of the object? Then just subtrackt that from Now() when you want to know how long the object has existed.
Why not use System.Diagnostics.Stopwatch
?
class Food
{
private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
public TimeSpan CookingTime
{
get { return _stopwatch.Elapsed; }
}
}
I notice that your cookingTime
field is static. If you are somehow totalling the times of multiple foods, then you might keep a list (static or otherwise) of Stopwatches, and whenever you need to know the total time, you could sum them all together.
精彩评论