0

Does anyone have a good idea for a timer? I've tried using the stopwatch but I must have done something wrong, I simply wish to have a int value go up once per second and have to ability to reset it.

This is my failed piece of code:

//Timer systemet
Stopwatch Timer = new Stopwatch();
Timer.Start();

TimeSpan ts = Timer.Elapsed;
double seconds = ts.Seconds;

//interval
if(seconds >= 8)
{
    Text = Text + 1;
    Timer.Stop();
}
Martin
  • 1
  • 1
    Welcome. A stopwatch in .NET is much like a real-life stopwatch: You can measure time with it. It's not meant for periodically invoking something like adding a value. Take a look at [this thread](https://stackoverflow.com/questions/186084/how-do-you-add-a-timer-to-a-c-sharp-console-application), I'm sure that you'll find the information you need there. – devsmn Jun 02 '20 at 07:29
  • 1
    See also https://stackoverflow.com/questions/10317088/why-there-are-5-versions-of-timer-classes-in-net – JonasH Jun 02 '20 at 07:38
  • Please check out this [gist](https://gist.github.com/qwertie/6706409) as well. – Peter Csala Jun 02 '20 at 07:49

2 Answers2

1

I see you've tagged this question with XNA and MonoGame. Typically, in game frameworks like this you don't use typical timers and stopwatches.

In MonoGame you would normally do something like this:

private float _delay = 1.0f;
private int _value = 0;

protected override void Update(GameTime gameTime)
{
    var deltaSeconds = (float) gameTime.ElapsedGameTime.TotalSeconds;

    // subtract the "game time" from your timer
    _delay -= deltaSeconds;

    if(_delay <= 0)
    {
        _value += 1;    // increment your value or whatever
        _delay = 1.0f;  // reset the timer
    }
}

Of course, this is the absolute simplest example. You can get more fancy and create a custom class to do the same thing. This way you can create multiple timers. There are examples of this in MonoGame.Extended which you're welcome to borrow the code from.

craftworkgames
  • 9,437
  • 4
  • 41
  • 52
0

Easiest way is to use System.Timers.Timer.

Example:

using System.Timers;

class Program
{
        static void Main(string[] args)
        {
            Timer t = new Timer(_period);
            t.Elapsed += TimerTick;
            t.Start();

        }

        static void TimerTick(Object source, ElapsedEventArgs e)
        {
            //your code
        }
}

If you need more variable Timer, you can use System.Threading.Timer (System.Timers.Timer is basically wrapper around this class).

Example:

using System.Threading;

class Program
{
        static void Main(string[] args)
        {
            Timer t = new Timer(TimerTick, new AutoResetEvent(false), _dueTime, _period);

        }

        static void TimerTick(Object state)
        {
            //your code
        }
}
David Pivovar
  • 115
  • 1
  • 10