Reputation: 11
I have created a simple class Engine. Here is the constructor :
public Engine() : base()
{
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Interval = 500;
timer.AutoReset = true;
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
CurrentTime = CurrentTime.AddMilliseconds(timer.Interval);
}
Two methods are associated to the class Engine :
public void Play(double speed)
{
timer.Interval = speed;
timer.Start();
}
public void Pause() {
timer.Stop();
Console.WriteLine(CurrentTime.ToString());
}
Theses methods are called from another class :
Engine engine = new Engine();
engine.Play(1000);
engine.Pause();
The problem occurs when calling the method Pause(). It seems that this call creates a new instance of Engine since the given CurrentTime is 01/01/0001 00:00:00. At least, the instance of Timer named timer is not stopped. I do not understand that behaviour.
A possible solution may be to force Engine to be singleton class (it works). However, I may need to create several instances of Engine. Any ideas ? Thanks.
Upvotes: 1
Views: 316
Reputation: 18168
CurrentTime hasn't been assigned to yet when you call Pause(). It is still the default value. This is happening because you call Pause() right after you call Play(). The timer has not had to a chance to get invoked yet.
Upvotes: 3