Question

I need to make a timer that will exit my program after 3 seconds - when a Bool is set to true - how can I do so? I have tried using a few basic timers in a new class, but this doesn't seem to work. I used the timer here http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx but it isn't working.

private static System.Timers.Timer aTimer;

public static void Main()
{
    // Create a timer with a ten second interval.
    aTimer = new System.Timers.Timer(10000);

    // Hook up the Elapsed event for the timer.
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

    // Set the Interval to 2 seconds (2000 milliseconds).
    aTimer.Interval = 2000;
    aTimer.Enabled = true;

}

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Game1.timedOrNo = true
}

}

Was it helpful?

Solution

Assuming you use XNA (from the tag list) you should have a following method in your Game class:

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
}

So you need to check if 3 seconds elapsed, and then exit:

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
    if (gameTime.TotalGameTime.TotalSeconds >= 3)
        this.Exit;
}

OTHER TIPS

Assuming you actually have aTimer.Start(); somewhere in your code, with what you posted the timer will indeed trigger the OnTimedEvent after two seconds and set your bool to true. All you need to do now is check the state of the bool somewhere, preferably in the Update method of Game1 with the Exit method like this :

protected override void Update(GameTime gameTime)
{
    if (timedOrNo)
    {
        Exit();
    }
}

As an alternative, since you can only exit once, the boolean is not really needed and you can close the application directly when the timer triggers :

private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    Game1.Exit();
}

As a side note, you should initiate the Interval directly in the constructor with new System.Timers.Timer(2000); instead of setting it to 10 seconds and then immediately to 2 manually. Also, you should change the 2000 to 3000 if you want it to exit after three seconds like you initially asked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top