C# event debounce

后端 未结 14 1088
南旧
南旧 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:34

    Simply remember the latest 'hit:

    DateTime latestHit = DatetIme.MinValue;
    
    private void eventRxVARxH(MachineClass Machine)
    {
        log.Debug("Event fired");
        if(latestHit - DateTime.Now < TimeSpan.FromXYZ() // too fast
        {
            // ignore second hit, too fast
            return;
        }
        latestHit = DateTime.Now;
        // it was slow enough, do processing
        ...
    }
    

    This will allow a second event if there was enough time after the last event.

    Please note: it is not possible (in a simple way) to handle the last event in a series of fast events, because you never know which one is the last...

    ...unless you are prepared to handle the last event of a burst which is a long time ago. Then you have to remember the last event and log it if the next event is slow enough:

    DateTime latestHit = DatetIme.MinValue;
    Machine historicEvent;
    
    private void eventRxVARxH(MachineClass Machine)
    {
        log.Debug("Event fired");
    
        if(latestHit - DateTime.Now < TimeSpan.FromXYZ() // too fast
        {
            // ignore second hit, too fast
            historicEvent = Machine; // or some property
            return;
        }
        latestHit = DateTime.Now;
        // it was slow enough, do processing
        ...
        // process historicEvent
        ...
        historicEvent = Machine; 
    }
    

提交回复
热议问题