SpinLockSpinLock

SpinLock 結構是一個低階、互斥的同步處理基本類型,會在等候取得鎖定期間進行微調。The SpinLock structure is a low-level, mutual-exclusion synchronization primitive that spins while it waits to acquire a lock. 在多核心電腦上,預期等候時間很短且競爭最少時,SpinLock 可以優於其他類型鎖定的方式執行。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. 不過,我們建議您只有在藉由分析 System.Threading.Monitor 方法進行判斷時,或 Interlocked 方法大幅減慢程式的效能,才使用 SpinLockHowever, 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.

即使 SpinLock 尚未取得鎖定,還是可能會讓出執行緒的時間配量。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. 當您使用 SpinLock 時,確保沒有任何執行緒可以保留鎖定超過一個非常短暫的時間範圍,而且沒有執行緒可以在保留鎖定時加以封鎖。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.

由於 SpinLock 是一個實值類型,因此,如果您想要讓兩個複本參考同一個鎖定,就必須明確地以傳址方式傳遞它。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.

如需如何使用此類型的詳細資訊,請參閱 System.Threading.SpinLockFor more information about how to use this type, see System.Threading.SpinLock. 如需範例,請參閱如何:使用 SpinLock 進行低階同步處理For an example, see How to: Use SpinLock for Low-Level Synchronization.

SpinLock支援 執行緒 - 追蹤 模式,可讓您在開發階段使用,以協助追蹤在特定時間保留鎖定的執行緒。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. 如需詳細資訊,請參閱如何:啟用 SpinLock 中的執行緒追蹤模式For more information, see How to: Enable Thread-Tracking Mode in SpinLock.

另請參閱See also