Skip to content

Instantly share code, notes, and snippets.

@seesharper
Created December 14, 2015 11:39
Show Gist options
  • Select an option

  • Save seesharper/bd0bb37c0f287e7a092e to your computer and use it in GitHub Desktop.

Select an option

Save seesharper/bd0bb37c0f287e7a092e to your computer and use it in GitHub Desktop.
RunOnce v2
/// <summary>
/// A thread safe class that ensures that a given
/// <see cref="Action"/> is only executed once.
/// </summary>
public class RunOnce
{
private Action action;
private bool hasExecuted;
private readonly object lockObject = new object();
/// <summary>
/// Initializes a new instance of the <see cref="RunOnce"/> class.
/// </summary>
/// <param name="action">The <see cref="Action"/> delegate to be executed once.</param>
public RunOnce(Action action)
{
this.action = action;
}
/// <summary>
/// Executes the <see cref="Action"/> only if not already executed.
/// </summary>
public void Run()
{
if (hasExecuted)
{
return;
}
lock (lockObject)
{
if (hasExecuted)
{
return;
}
action(); //Takes 10 sekconds
hasExecuted = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment