Skip to content

Instantly share code, notes, and snippets.

@z3nth10n
Last active April 2, 2019 22:43
Show Gist options
  • Save z3nth10n/052e6660c392d6a4e48290e9a6ae36f8 to your computer and use it in GitHub Desktop.
Save z3nth10n/052e6660c392d6a4e48290e9a6ae36f8 to your computer and use it in GitHub Desktop.
ThreadSafeBool
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