Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created July 9, 2024 20:49
Show Gist options
  • Save NickStrupat/283ba0afa29ea78922b60e398351b1de to your computer and use it in GitHub Desktop.
Save NickStrupat/283ba0afa29ea78922b60e398351b1de to your computer and use it in GitHub Desktop.
A thread-safe utility class that returns the `once` value once ever, and then the `other` value from then on.
public sealed class OnceThenOther<T>(T once, T other)
{
private Int32 flag = 0;
// Checking the flag value normally before exchanging it atomically is an optimization with two parts:
// A) Contentious first access will all synchronize on the atomic exchange
// B) Subsequent accesses will see the local cached value of `1`, so they won't have to perform the heavier atomic exchange
public T Value => flag == 0 && Interlocked.Exchange(ref flag, 1) == 0 ? once : other;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment