System.Threading.SpinLock Structure

Provides a mutual exclusion lock primitive where a thread trying to acquire the lock waits in a loop repeatedly checking until the lock becomes available.

See Also: SpinLock Members


[System.Diagnostics.DebuggerDisplay("IsHeld = {IsHeld}")]
public struct SpinLock


For an example of how to use a Spin Lock, see How to: Use SpinWait and SpinLock.

Spin locks can be used for leaf-level locks where the object allocation implied by using a System.Threading.Monitor, in size or due to garbage collection pressure, is overly expensive. A spin lock can be useful in to avoid blocking; however, if you expect a significant amount of blocking, you should probably not use spin locks due to excessive spinning. Spinning can be beneficial when locks are fine-grained and large in number (for example, a lock per node in a linked list) and also when lock hold-times are always extremely short. In general, while holding a spin lock, one should avoid any of these actions:

System.Threading.SpinLock should only be used after you have been determined that doing so will improve an application's performance. It is also important to note that System.Threading.SpinLock is a value type, for performance reasons. For this reason, you must be very careful not to accidentally copy a System.Threading.SpinLock instance, as the two instances (the original and the copy) would then be completely independent of one another, which would likely lead to erroneous behavior of the application. If a System.Threading.SpinLock instance must be passed around, it should be passed by reference rather than by value.

Do not store System.Threading.SpinLock instances in readonly fields.


Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: