You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readarr/src/NzbDrone.Common/TPL/Debouncer.cs

71 lines
1.6 KiB

using System;
namespace NzbDrone.Common.TPL
{
public class Debouncer
{
private readonly Action _action;
private readonly System.Timers.Timer _timer;
private readonly bool _executeRestartsTimer;
private volatile int _paused;
private volatile bool _triggered;
public Debouncer(Action action, TimeSpan debounceDuration, bool executeRestartsTimer = false)
{
_action = action;
_timer = new System.Timers.Timer(debounceDuration.TotalMilliseconds);
_timer.Elapsed += timer_Elapsed;
_executeRestartsTimer = executeRestartsTimer;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_paused == 0)
{
_triggered = false;
_timer.Stop();
_action();
}
}
public void Execute()
{
lock (_timer)
{
_triggered = true;
if (_executeRestartsTimer)
{
_timer.Stop();
}
if (_paused == 0)
{
_timer.Start();
}
}
}
public void Pause()
{
lock (_timer)
{
_paused++;
_timer.Stop();
}
}
public void Resume()
{
lock (_timer)
{
_paused--;
if (_paused == 0 && _triggered)
{
_timer.Start();
}
}
}
}
}