0

In a multithreaded scenario does it make sense to declare a boolean property of a class that is read and set by many threads simultaneously in the following way in C# .net?

public class MyClass 
{
    private long _check;

    public bool Check 
    {
        get => Interlocked.Read(ref _check) == 1;
        set => Interlocked.Exchange(ref _check, Convert.ToInt64(value));
    }
}
renzo
  • 85
  • 1
  • 9

1 Answers1

2

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.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104