none
Interlocked methods on a property RRS feed

  • Question

  • Hi,

    If I have a property in a class, the compiler lets me do:

          Interlocked.Exchange(property, value)

    If the property is readonly, the get method is called.

    If the property is writeonly, the program does not compile.

    If the property is read/write, the get method is called and then the set method with value as the actual parameter.

    What about the atomic guarantees the documentation tells when using a field along with Interlocked?

    Are they gone with this usage, even if the property is a simple one with a trivial back storage field of the same type?

    Thank you very much.

    Thursday, October 25, 2012 11:26 AM

Answers

  • "I've tested in Visual Basic"

    I see... it certainly doesn't compile in C#. Looks like what Visual Basic does is something like (in C# syntax):

    int value = Property;
    Interlocked.Exchange(ref value, 42);
    Property = value;
    
    In short it executes the interlocked operation on a local copy of that property. The resulting code is no longer atomic. 
    Thursday, October 25, 2012 12:02 PM
    Moderator

All replies

  • Interlocked.Exchange on a property? That can't be, such code doesn't make sense and it doesn't compiler. Perhaps you mean a field?
    Thursday, October 25, 2012 11:33 AM
    Moderator
  • Interlocked.Exchange on a property? That can't be, such code doesn't make sense and it doesn't compiler. Perhaps you mean a field?

    It does compile (I've tested in Visual Basic), and it works as I have described.

    There must be some magic under the hood, because the property back storage field ends up receiving the value and the former value is returned (get and set methods get called).

    But I was wondering if I lose atomicity in doing so, even if the property is a simple one, or there are any compiler optimizations that may work here and preserve the automicity.

    Thank you.


    • Edited by mulhacén Thursday, October 25, 2012 11:58 AM
    Thursday, October 25, 2012 11:58 AM
  • "I've tested in Visual Basic"

    I see... it certainly doesn't compile in C#. Looks like what Visual Basic does is something like (in C# syntax):

    int value = Property;
    Interlocked.Exchange(ref value, 42);
    Property = value;
    
    In short it executes the interlocked operation on a local copy of that property. The resulting code is no longer atomic. 
    Thursday, October 25, 2012 12:02 PM
    Moderator