C# debouncer

Date: 2020-10-12
using System;
using System.Threading;
using System.Threading.Tasks;

public class Debouncer : IDisposable
{
	public Debouncer(TimeSpan interval, Action action)
	{
		_interval = interval;
		_action = action;
	}
	private volatile Timer? _timer;
	private readonly TimeSpan _interval;
	private readonly Action _action;
	public void Debounce()
	{
		Reset();
		_timer = new Timer(OnTimer, null, (int)_interval.TotalMilliseconds, Timeout.Infinite);
	}

	private void OnTimer(object state)
	{
		Reset();
		_action?.Invoke();
	}

	private void Reset()
	{
		_timer?.Dispose();
		_timer = null;
	}

	public void Dispose() => Reset();
}

public class Program
{
	async static Task Main()
	{
		Console.WriteLine("start");
		var d = new Debouncer(TimeSpan.FromSeconds(2), () => Console.WriteLine("d"));
		Console.WriteLine("abc");
		d.Debounce();
		await Task.Delay(1000);
		Console.WriteLine("abc");
		d.Debounce();
		await Task.Delay(2500);
		Console.WriteLine("abc");
		d.Debounce();
		await Task.Delay(4000);
		Console.WriteLine("end");
	}
}
41270cookie-checkC# debouncer