SpinLock Structure

Task Parallel System.Threading

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.

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

Syntax

Visual Basic (Declaration)
<ComVisibleAttribute(False)> _
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
	ExternalThreading := True)> _
Public Structure SpinLock
C#
[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public struct SpinLock

Remarks

Spin locks can be used for leaf-level locks where the object allocation implied by using a Monitor, in size or due to garbage collection pressure, is overly expensive. Avoiding blocking is another reason that a spin lock can be useful, however if you expect any significant amount of blocking, you are probably best not using 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) as well as when lock hold times are always extremely short. In general, while holding a spin lock, one should avoid blocking, calling anything that itself may block, holding more than one spin lock at once, making dynamically dispatched calls (interface and virtuals), making statically dispatched calls into any code one doesn't own, or allocating memory.

SpinLock should only be used when it's been determined that doing so will improve an application's performance. It's also important to note that SpinLock is a value type, for performance reasons. As such, one must be very careful not to accidentally copy a 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 SpinLock instance must be passed around, it should be passed by reference rather than by value.

Do not store SpinLock instances in readonly fields.

All members of SpinLock are thread-safe and may be used from multiple threads concurrently.

See Also