Skip to content

Instantly share code, notes, and snippets.

@wi7a1ian
Last active March 18, 2019 10:04
Show Gist options
  • Save wi7a1ian/319a4b4dd967e34609df4e50ff1cd15a to your computer and use it in GitHub Desktop.
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
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
}
@wi7a1ian
Copy link
Author

wi7a1ian commented Mar 7, 2019

Useful for protecting commands or button events or text-boxes from multiple input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment