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.
It seems that this call creates a new instance of EngineI can guarantee that isn't the issue. You have some other bug going on here. Do you keep a reference toengineonce created?