谁有一个好的想法,在C#中做一个基本的定时器?

问题描述 投票:0回答:1

有谁有一个定时器的好主意吗?我试过使用秒表,但我一定是做错了什么,我只是想让一个int值每秒上升一次,并有能力重置它。

这是我的一段失败的代码。

//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();
}
c# xna monogame stopwatch
1个回答
1
投票

我看到你把这个问题标记为XNA和MonoGame。通常,在这样的游戏框架中,你不会使用典型的计时器和秒表。

在MonoGame中,你通常会做这样的事情。

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
    }
}

当然,这只是最简单的例子。你可以做得更花哨一些,创建一个自定义的 class 来做同样的事情。这样你就可以创建多个定时器。有 在MonoGame.Extended中就有这样的例子。 欢迎你借用其中的代码。


0
投票

最简单的方法是使用 System.Timers.Timer.

例子。

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
        }
}

如果你需要更多的变量Timer,你可以使用 System.Threading.Timer (System.Timers.Timer 基本上是这个类的封装器)。)

例子:

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
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.