Created
July 9, 2024 20:49
-
-
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.
This file contains 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
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