c# - Threading.SpinWait 结构与 Thread.SpinWait 方法

标签 c# multithreading

我想知道 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/

相关文章:

java - 线程/处理程序错误 - 尚未发布指定的消息队列同步屏障 token

c# - 自定义 HTML 帮助器类是否违反了 ASP.NET MVC 模型?

c# - 图表中间的图表集(0,0)

c++ - 启动没有线程实例名称的线程

Android最佳实践: Loading stuff in background and storing results acceptable from multiple activities?

multithreading - 当我尝试启动不同的线程时如何避免重复作业(每个核心一个)?

c# - 为什么参数会这样?

c# - C# 中的 Excel 函数目标求等价算法

c# - await Task.WhenAll 看似完成,但它永远不会到达下一行代码

java - 网络游戏状态更改时小程序游戏更新屏幕