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

后端 未结 4 446
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  清歌不尽
    2021-01-15 06:46

    I would not use a Stopwatch or anything other Timer-like. Instead just store the time of the method call and only execute the subsequent calls if the difference between the current and the stored time is bigger than 100ms.

    You could implement a helper class to do this in a more general way:

    public class TimedGate
    {
         private DateTime m_Last;
         private TimeSpan m_Gap;
    
         public TimedGate(TimeSpan gap)
         {
             m_Gap = gap;
         }
    
         public bool TryEnter()
         {            
             DateTime now = DateTime.UtcNow;
             if (now.Subtract(m_Last) > m_Gap)
             {
                  m_LastEntered = now;   
                  return true;                 
             }
             return false;  
         }
    }
    

    Use it like this:

    TimedGate m_UpdateGate = new TimedGate(TimeSpan.FromMilliseconds(100));
    
    private void Update()
    {
        if (m_UpdateGate.TryEnter())
        {
            Console.WriteLine("!update");
    
            // do work here
        }
        else
        {
            Console.WriteLine("!skip update");
        }
    }
    

提交回复
热议问题