C# wait timeout before calling method and reset timer on consecutive calls

Viewed 4249

I have a event in my code that can possibly get fired multiple times a second at some moment.

However I would like to implement a way to make that method wait 500ms before really firing, if the method gets called again before those 500ms are over, reset the timer and wait for 500ms again.

Coming from javascript I know this is possible with setTimeout or setInterval. However I'm having trouble figuring out how I could implement such a thing in C#.

4 Answers

Just writen super simple class with System.Threading.Thread; With a little different approach Usage.

var delayedCaller = new DelayedTimeout(() => HelloWorld(123), 500, false);
delayedCaller.ResetTimer();
delayedCaller.ResetTimer();

Currently, you can do it very simple with the following class

public class DelayedTimeout
{
    readonly Timer _timer;
    readonly int _timeoutMs;

    public DelayedTimeout(TimerCallback callback, int timeoutMs, bool startNow)
    {
        _timeoutMs = timeoutMs;
        // Should we start now
        var currentTimeoutMs = startNow ? _timeoutMs : Timeout.Infinite;
        _timer = new Timer(callback, null, currentTimeoutMs, Timeout.Infinite);
    }

    // Constructor overloading
    public DelayedTimeout(Action callback, int timeoutMs, bool startNow) :
        this(delegate (object? obj) { callback.Invoke(); }, timeoutMs, startNow)
    {}

    public void ResetTimer()
    {
        _timer.Change(Timeout.Infinite, Timeout.Infinite); // Stop the timer
        _timer.Change(_timeoutMs, Timeout.Infinite); // Stop the timer
    }
}
Related