Created
January 8, 2024 15:11
-
-
Save codejockie/7485679194ded20bcfa1d755f2d738b3 to your computer and use it in GitHub Desktop.
A simple debouncer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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