Created
December 14, 2015 11:39
-
-
Save seesharper/bd0bb37c0f287e7a092e to your computer and use it in GitHub Desktop.
RunOnce v2
This file contains hidden or 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
| /// <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