简体   繁体   中英

How to create a timer in C# without using System.Timers.Timer or System.Threading.Timer

Is it possible to create a timer in C# without using System.Timers.Timer or System.Threading.Timer ?

I am using timers in a Unity project (C#) and I am trying to export a WebGL project. And threads are not supported for the moment in Unity WebGL exports.

And it seems that using System.Timers.Timer > Elapsed event runs on a separate thread. (?)

AC# Timer has the ability to trigger a callback function once the specified time has elapsed and thus runs a check in a separate thread.

If you only care about the amount of time elapsed and you don't want to use Unity's Time.deltaTime capabilities, you can use DateTime to keep track of the time. Here is a basic example class that provides this behavior.

public class SimpleTimer
{
    private DateTime StartTime;
    private DateTime LastTime;
    private bool running;

    public double ElaspedTime { get { return GetElapsedTime(); } }

    public void Start()
    {
        StartTime = DateTime.Now;
        running = true;
    }

    public void Restart()
    {
        Start();
    }

    public double GetElapsedTime()
    {
        if (!running)
            throw new Exception("SimpleTimer not running! Must call Start() prior to querying the Elapsed Time.");

        LastTime = DateTime.Now;
        var elaspedTime = LastTime - StartTime;

        return elaspedTime.TotalMilliseconds;
    }

    public double GetElapsedTimeAndRestart()
    {
        var elaspedTime = GetElapsedTime();
        Restart();

        return elaspedTime;
    }
}

...and here is an example of use:

var timer = new SimpleTimer();
timer.Start();

//Prints the total time each iteration
for(var i = 1; i <=1000; i++)
{
    System.Threading.Thread.Sleep(5);
    Console.WriteLine("Loop " + i + ": Elasped Time = " + timer.ElaspedTime + " ms");
}

timer.Restart();

//Prints roughly 5ms each iteration
for (var i = 1; i <= 1000; i++)
{
    System.Threading.Thread.Sleep(5);                
    Console.WriteLine("Loop " + i + ": Elasped Time = " + timer.ElaspedTime + " ms");
    timer.Restart();
}

This could be expanded to call a function once the desired elapsed time has been reached, but you would need to place a call to a check method some place in your code that gets run often and consistently. (Like in an FSM loop)

Hope this helps!

I think you can do something like:

public class MyTimer : MonoBehaviour
{
float myTime = 0.0f;
void Update()
{
UpdateTime();
}

public void UpdateTime()
{
myTime += Time.deltaTime;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM