Last active
March 18, 2019 10:04
-
-
Save wi7a1ian/319a4b4dd967e34609df4e50ff1cd15a to your computer and use it in GitHub Desktop.
Defers performing the action until after time elapses. Repeated calls will reschedule the action if it has not already been performed. Good for handling UI actions when someone has *Parkinson's disease* #wpf #csharp
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
sealed class DeferredAction : IDisposable | |
{ | |
private Timer timer; | |
private bool disposed = false; | |
/// <summary> | |
/// Creates a new DeferredAction. | |
/// </summary> | |
/// <param name="action"> | |
/// The action that will be deferred. It is not performed until after <see cref="Defer"/> is called. | |
/// </param> | |
public static DeferredAction Create(Action action) | |
{ | |
if (action == null) | |
{ | |
throw new ArgumentNullException(nameof(action)); | |
} | |
return new DeferredAction(action); | |
} | |
private DeferredAction(Action action) | |
{ | |
this.timer = new Timer(new TimerCallback(delegate | |
{ | |
Application.Current.Dispatcher.Invoke(action); | |
})); | |
} | |
/// <summary> | |
/// Defers performing the action until after time elapses. Repeated calls will reschedule the action | |
/// if it has not already been performed. | |
/// </summary> | |
public void Defer(TimeSpan delay) | |
{ | |
this.timer.Change(delay, TimeSpan.FromMilliseconds(-1)); | |
} | |
#region IDisposable implementation | |
public void Dispose() | |
{ | |
Dispose(true); // Freed all the resources | |
GC.SuppressFinalize(this); | |
} | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposed) | |
return; | |
if (disposing && timer != null) | |
{ | |
timer.Dispose(); | |
timer = null; | |
} | |
disposed = true; | |
} | |
~DeferredAction() | |
{ | |
Dispose(false); // We already freed all the resources | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Useful for protecting commands or button events or text-boxes from multiple input.