Skip to content

Instantly share code, notes, and snippets.

@jltrem
Last active August 29, 2015 14:04
Show Gist options
  • Save jltrem/741964d1e14a799019f2 to your computer and use it in GitHub Desktop.
Save jltrem/741964d1e14a799019f2 to your computer and use it in GitHub Desktop.
/// <summary>
/// Run an action after the specified delay
/// </summary>
/// <param name="delayMillis">millisecond delay before running an action</param>
/// <param name="doOnce">action to run</param>
public static void RunOneShot(int delayMillis, Action doOnce)
{
if (delayMillis <= 0) throw new ArgumentException("RunOneShot delayMillis argument must be greater than 0");
if (doOnce == null) throw new ArgumentException("RunOneShot doOnce argument cannot be null");
// create a one-shot timer
var t = new System.Timers.Timer(delayMillis) { AutoReset = false, Enabled = true };
// define the handler to be called at the elapsed time
t.Elapsed += (caller, e) =>
{
// dispose the timer because it is only used once
var timer = caller as System.Timers.Timer;
if (timer != null)
{
timer.Dispose();
}
// run the provided action
doOnce();
};
// make it happen
t.Start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment