Thread.SpinWait(Int32) Method


导致线程等待由 iterations 参数定义的时间量。Causes a thread to wait the number of times defined by the iterations parameter.

 static void SpinWait(int iterations);
public static void SpinWait (int iterations);
static member SpinWait : int -> unit
Public Shared Sub SpinWait (iterations As Integer)



定义线程等待的时间长短的 32 位有符号整数。A 32-bit signed integer that defines how long a thread is to wait.


SpinWait 方法对于实现锁定很有用。The SpinWait method is useful for implementing locks. .NET Framework 中的类(如 MonitorReaderWriterLock)在内部使用此方法。Classes in the .NET Framework, such as Monitor and ReaderWriterLock, use this method internally. SpinWait 实质上是将处理器放入非常紧密的循环,并使用 iterations 参数指定的循环计数。SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. 因此,等待时间取决于处理器的速度。The duration of the wait therefore depends on the speed of the processor.

Sleep 方法对比。Contrast this with the Sleep method. 调用 Sleep 的线程将生成其处理器时间的当前切片的其余部分(即使指定的间隔为零)。A thread that calls Sleep yields the rest of its current slice of processor time, even if the specified interval is zero. Sleep 指定一个非零间隔后,线程计划程序将从线程计划程序中删除线程,直到时间间隔结束。Specifying a non-zero interval for Sleep removes the thread from consideration by the thread scheduler until the time interval has elapsed.

对于普通的应用程序,SpinWait 通常不起作用。SpinWait is not generally useful for ordinary applications. 在大多数情况下,应使用 .NET Framework 提供的同步类;例如,调用 Monitor.Enter 或包装 Monitor.Enter 的语句(在 Visual Basic 中lock C#或 SyncLockIn most cases, you should use the synchronization classes provided by the .NET Framework; for example, call Monitor.Enter or a statement that wraps Monitor.Enter (lock in C# or SyncLock in Visual Basic).


在极少数情况下,避免使用上下文切换很有用,例如,当你知道状态更改即将发生时,请在循环中调用 SpinWait 方法。In the rare case where it is advantageous to avoid a context switch, such as when you know that a state change is imminent, make a call to the SpinWait method in your loop. SpinWait 执行的代码旨在防止具有多个处理器的计算机上出现的问题。The code SpinWait executes is designed to prevent problems that can occur on computers with multiple processors. 例如,在具有多个采用超线程技术的 Intel 处理器的计算机上,SpinWait 在某些情况下防止处理器不足。For example, on computers with multiple Intel processors employing Hyper-Threading technology, SpinWait prevents processor starvation in certain situations.

Applies to