C# event debounce

后端 未结 14 1082
南旧
南旧 2020-11-28 06:22

I\'m listening to a hardware event message, but I need to debounce it to avoid too many queries.

This is an hardware event that sends the machine status and I have t

14条回答
  •  自闭症患者
    2020-11-28 06:43

    I know I'm a couple hundred thousand minutes late to this party but I figured I'd add my 2 cents. I'm surprised no one has suggested this so I'm assuming there's something I don't know that might make it less than ideal so maybe I'll learn something new if this gets shot down. I often use a solution that uses the System.Threading.Timer's Change() method.

    using System.Threading;
    
    Timer delayedActionTimer;
    
    public MyClass()
    {
        // Setup our timer
        delayedActionTimer = new Timer(saveOrWhatever, // The method to call when triggered
                                       null, // State object (Not required)
                                       Timeout.Infinite, // Start disabled
                                       Timeout.Infinite); // Don't repeat the trigger
    }
    
    // A change was made that we want to save but not until a
    // reasonable amount of time between changes has gone by
    // so that we're not saving on every keystroke/trigger event.
    public void TextChanged()
    {
        delayedActionTimer.Change(3000, // Trigger this timers function in 3 seconds,
                                        // overwriting any existing countdown
                                  Timeout.Infinite); // Don't repeat this trigger; Only fire once
    }
    
    // Timer requires the method take an Object which we've set to null since we don't
    // need it for this example
    private void saveOrWhatever(Object obj) 
    {
        /*Do the thing*/
    }
    

提交回复
热议问题