Skip to content

Instantly share code, notes, and snippets.

@codejockie
Created January 8, 2024 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codejockie/7485679194ded20bcfa1d755f2d738b3 to your computer and use it in GitHub Desktop.
Save codejockie/7485679194ded20bcfa1d755f2d738b3 to your computer and use it in GitHub Desktop.
A simple debouncer
using System;
using System.Threading;
public class Debouncer : IDisposable
{
private Thread thread;
private volatile Action action;
private volatile int delay = 0;
private volatile int frequency;
public void Debounce(Action action, int delay = 250, int frequency = 10)
{
this.action = action;
this.delay = delay;
this.frequency = frequency;
if (this.thread == null)
{
this.thread = new Thread(() => this.RunThread());
this.thread.IsBackground = true;
this.thread.Start();
}
}
private void RunThread()
{
while (true)
{
this.delay -= this.frequency;
Thread.Sleep(this.frequency);
if (this.delay <= 0 && this.action != null)
{
this.action();
this.action = null;
}
}
}
public void Dispose()
{
if (this.thread != null)
{
this.thread.Abort();
this.thread = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment