SpinLock throwing SynchronizationLockException SpinLock throwing SynchronizationLockException multithreading multithreading

SpinLock throwing SynchronizationLockException


SpinLock is a struct, and you are reading it from a readonly field. The C# spec says that in this case, in order to call a potentially mutating function, the struct must be copied to a mutable local variable. This happens under the covers.

Your calls to Enter and Exit happen on a fresh copy of your lock. For that reason, Enter is operating on an unlocked lock.

Don't make the SpinLock variable readonly because it is being mutated.