SpinLock是结构体, 相似于monitor, 可是垃圾回收付出的代价更小, 若是须要用到大量的lock而且执行的时间很是短,就能够利用SpinLock, 须要注意的是SpinLock既然是结构体,传递时会产生副本,所以老是经过Ref来传递。 ui
The SpinLock structure is a low-level, mutual-exclusion synchronization primitive that spins while it waits to acquire a lock. On multicore computers, when wait times are expected to be short and when contention is minimal, SpinLock can perform better than other kinds of locks. However, we recommend that you use SpinLock only when you determine by profiling that the System.Threading.Monitor method or the Interlocked methods are significantly slowing the performance of your program. this
SpinLock may yield the time slice of the thread even if it has not yet acquired the lock. It does this to avoid thread-priority inversion, and to enable the garbage collector to make progress. When you use a SpinLock, ensure that no thread can hold the lock for more than a very brief time span, and that no thread can block while it holds the lock. spa
Because SpinLock is a value type, you must explicitly pass it by reference if you intend the two copies to refer to the same lock. debug
For more information about how to use this type, see System.Threading.SpinLock. For an example, see How to: Use SpinLock for Low-Level Synchronization. orm
SpinLock supports a thread-tracking mode that you can use during the development phase to help track the thread that is holding the lock at a specific time. Thread-tracking mode is very useful for debugging, but we recommend that you turn it off in the release version of your program because it may slow performance. For more information, see How to: Enable Thread-Tracking Mode in SpinLock. ci