我想知道 Threading.Thread.SpinWait
方法和 Threading.SpinWait
结构之间是否有任何区别。
特别是,在应用程序中实现 spinwait 的惯用方法是什么:
Thread.SpinWait(1);
或
SpinWait spinWait = new SpinWait();
// ...
spinWait.SpinOnce();
最佳答案
结果是documentation SpinWait 结构的建议不要直接使用 Thread.SpinWait() 方法。正确的做法是:
SpinWait spinWait = new SpinWait();
// ...
spinWait.SpinOnce();
SpinWait encapsulates common spinning logic. On single-processor machines, yields are always used instead of busy waits, and on computers with Intel processors employing Hyper-Threading technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of spinning and true yielding.
SpinWait is a value type, which means that low-level code can utilize SpinWait without fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications. In most cases, you should use the synchronization classes provided by the .NET Framework, such as Monitor. For most purposes where spin waiting is required, however, the SpinWait type should be preferred over the Thread.SpinWait method.
http://www.albahari.com/threading/part5.aspx#_SpinLock_and_SpinWait添加一些细节:
In its current implementation, SpinWait performs CPU-intensive spinning for 10 iterations before yielding. However, it doesn’t return to the caller immediately after each of those cycles: instead, it calls
Thread.SpinWait
to spin via the CLR (and ultimately the operating system) for a set time period. This time period is initially a few tens of nanoseconds, but doubles with each iteration until the 10 iterations are up. This ensures some predictability in the total time spent in the CPU-intensive spinning phase, which the CLR and operating system can tune according to conditions. Typically, it’s in the few-tens-of-microseconds region — small, but more than the cost of a context switch. On a single-core machine, SpinWait yields on every iteration. You can test whether SpinWait will yield on the next spin via the property NextSpinWillYield. If a SpinWait remains in “spin-yielding” mode for long enough (maybe 20 cycles) it will periodically sleep for a few milliseconds to further save resources and help other threads progress.
简而言之,据我了解,Threading.Thread.SpinWait
执行实际的旋转,Threading.SpinWait
封装了它,以便它在几乎所有情况下都能正常工作.
关于c# - Threading.SpinWait 结构与 Thread.SpinWait 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69925397/