Loading...
Debounce is an event-handling technique that allows you to significantly limit the frequency of a certain action. The basic idea is to prevent a certain function from being executed multiple times in a short period of time by calling it only once after events have stopped arriving for a specified amount of time.
Debounce is generally used in the following cases:
• User interface event handling: For example, to prevent the event handler from executing multiple times when text is entered into an input field.
• Requests to the server: Reducing the number of requests sent to the server during rapid sequential changes such as autocomplete or real-time filters.
Examples of using Debounce in .Net
Explanation
1. DebounceDispatcher:
• DebounceAsync:
■ Uses CancellationTokenSource to cancel previous requests.
■ Cancels the previous request (_cts.Cancel()), creates a new CancellationTokenSource.
■ Waits for a given time interval (Task.Delay) and checks whether the request has been canceled.
■ Performs the action if no cancel was called.
2. Controller:
• Uses DebounceDispatcher to handle requests.
• It is ensured that only the latest requests from those received during the specified interval are executed.
This implementation should ensure that only one request will be executed when many identical requests are received in a short period of time. If the previous queries are still executing, check for additional runtime or configuration issues.
An example of using Debounce in .Net in a query with the same parameters
This implementation provides the ability to handle multiple requests with the same parameters by executing only one request within a given time period.
Explanation:
1. ConcurrentDictionary: It is used to store the time of the last query execution for each of the parameters. This allows you to securely perform checks and updates from multiple threads.
2. DebounceTime: Defines the debounce time (5 seconds).
3. Query Validation: When a new query arrives, we analyze whether a dictionary entry exists for that parameter and whether less than 5 seconds have passed since the last execution time. If so, we ignore the request.
4. Update the last execution time: If the request is new or more than 5 seconds have passed since the last execution time, we update the time in the dictionary and process the request.
https://youtu.be/4QyVMhFm884