Last active
April 2, 2019 22:43
-
-
Save z3nth10n/052e6660c392d6a4e48290e9a6ae36f8 to your computer and use it in GitHub Desktop.
ThreadSafeBool
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
using System.Threading; | |
namespace GTAMapper.Extensions.Threading | |
{ | |
/// <summary> | |
/// Thread safe enter once into a code block: | |
/// the first call to CheckAndSetFirstCall returns always true, | |
/// all subsequent call return false. | |
/// </summary> | |
public class ThreadSafeBool | |
{ | |
private static int NOTCALLED = 0, | |
CALLED = 1; | |
private int _state = NOTCALLED; | |
/// <summary>Explicit call to check and set if this is the first call</summary> | |
public bool Value | |
{ | |
get | |
{ | |
return Interlocked.Exchange(ref _state, CALLED) == NOTCALLED; | |
} | |
} | |
/// <summary>usually init by false</summary> | |
public static implicit operator ThreadSafeBool(bool called) | |
{ | |
return new ThreadSafeBool() { _state = called ? CALLED : NOTCALLED }; | |
} | |
public static implicit operator bool(ThreadSafeBool cast) | |
{ | |
if (cast == null) | |
return false; | |
return cast.Value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment