Your implementation of a volatile bool
field is overly complex. You can achieve exactly the same thing like this:
private bool _check;
public bool Check
{
get => Volatile.Read(ref _check);
set => Volatile.Write(ref _check, value);
}
...or even simpler like this:
public volatile bool Check;
The Interlocked.Exchange
is preferable to the Volatile.Write
only when you want to get the previous value as an atomic operation. Otherwise the Volatile.Write
has the same effect and it's more lightweight.
Whether having such a field is a good idea in the first place, depends on the scenario. If you have a loop and you want to use the field as a breaking mechanism, it might be a good idea. If you want to synchronize the access to some other shared state of your class, it's probably not.