1

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.

2
  • It seems that this call creates a new instance of Engine I can guarantee that isn't the issue. You have some other bug going on here. Do you keep a reference to engine once created? Commented May 31, 2011 at 15:27
  • 1
    Jean-Marie, could you recap the actual answer to your question? This might help others with similar problems. Also it is valuable if you accept an answer - this lets other people know this answer which answer was most valuable to you. See the faq for more details. Commented Jun 2, 2011 at 12:35

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

CurrentTime seems to get a correct value (for example 2011/05/31 12:50:00) until I call Pause(). Indeed I may call Pause() after a long time (these two methods Play() and Pause() are associated to buttons of a form))
@Heandel : thank you, i am going top check the rest of the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.