Take the 2-minute tour ×

Just reading through the MSDN page about new .NET 4.0 feature SpinLock and can not understand idea behind the following statement:

Do not store SpinLock instances in readonly fields.

My feelings that this is somehow related to value-type specifics but not sure how exactly and why. Could anybody bring more light on this point?

share|improve this question
@Chriseyre2000 : why you've deleted your answer? it is fine but of very low quality I believe this is why someone downvoted it. Just bring more details and undelete I will +1 anyway since you was the first who answered. Thanks! I've really overlooked MSDN page comment yu've mentioned –  sll Feb 10 '12 at 21:35

1 Answer 1

up vote 7 down vote accepted

The underlying problem is that the C# compiler creates a copy of a readonly value type field when you call a non-static method on it and executes that method on the copy - because the method could have side effects that change the value of the struct - which is not allowed for readonly fields.

For further clarification see "Mutating Readonly Structs".

share|improve this answer
Gross. I find it hard to believe that they would so something so recklass as make a mutable object a struct, let alone one as important as a lock. –  Jonathan Allen Feb 10 '12 at 21:32
+1 and thanks, great stuff! Shame to me that I was not aware of mutable readonly structs before. –  sll Feb 10 '12 at 21:36
@JonathanAllen SpinLock is meant as a most lightweight lock object. It is for advanced use-cases. –  usr Oct 9 '13 at 16:49
@sll The entire purpose of the SpinLock is that an instance method call mutates the struct. Specifically, when you do mySpinLock.Enter(ref wasLockSuccessful); then the method call changes the state of mySpinLock. Now, if mySpinLock is a field declared with readonly, it is the state of a copy of the field which is changed. The bool wasLockSuccessful is set to true. But when you examine the original (as opposed to the copy which was not kept) mySpinLock, then mySpinLock.IsHeld is still false. Removing the readonly modifier solves that. –  Jeppe Stig Nielsen Oct 17 '13 at 10:33

Your Answer


