Debounce
Debounce Class
The Debounce class is a utility class in C# used to prevent the rapid firing of events. Particularly useful in scenarios where an action should only be performed after an event has ceased to occur for a specified duration, like key-up events on textboxes that trigger searches.
Bounce Method
The Bounce
method is called whenever an event occurs. It resets the debounce timeout. If this method is not called again within that timeout, the action specified in the Debounce constructor will fire. The Bounce
method can optionally take a parameter, which will be passed to the action when it fires.
Example:
In the first example, the Bounce
method is called without a parameter, so when the action fires it won't receive any parameters. In the second example, the Bounce
method is called with an integer parameter, so the action will receive the last integer passed when it fires.
Disposing
When disposing the Debounce class that doesn't take any generic parameters, no additional callbacks will be fired.
When disposing the Debounce<T> class, there is an immediate one time fire of the bounce callback that has the latest value supplied. This is particularly useful when you need to dispose of a resource quickly, but still need to access the latest value in the pipeline without waiting on the bounce to fire.
Last updated