how to execute certain class method no more than once per 100ms?

后端 未结 4 402
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 05:51

I\'m writing trading software and need to QoS one method that should not be executed more often than 10 times per second. As I\'m begginer in C# and almost not familar with

4条回答
  •  梦毁少年i
    2021-01-15 06:23

    Stopwatches and timers are fairly expensive objects to use. You could simply hold a DateTime object as a variable and perform a comparison.

    DateTime lastCheck = DateTime.Now;
    
    private void update()
    {
        // DateTime.Subtract returns a TimeSpan
        int elapsed = DateTime.Now.Subtract(lastCheck).Milliseconds;
        if (elapsed < 100)
        {
            Console.WriteLine("!skip update " + elapsed.ToString());
            return;
        } else
        {
            Console.WriteLine("!update");
            lastCheck = DateTime.Now;
        }
        // do work here
    }
    

提交回复
热议问题