c# - Thread.sleep vs Monitor.Wait vs RegisteredWaitHandle?

标签 c# .net multithreading .net-4.0 clr

(以下项目有不同的目标,但我很想知道它们是如何“暂停”的)

问题

Thread.sleep - 它会影响系统的性能吗?它会占用线程等待吗?

Monitor.Wait 呢?他们“等待”的方式有什么不同?他们会在等待时占用线程吗?

RegisteredWaitHandle 怎么样?此方法接受等待时执行的委托(delegate) 句柄发出信号。在等待期间,它不会占用线程。

所以一些线程被暂停并且可以被委托(delegate)唤醒,而其他线程只是等待?旋转 ?

有人可以把事情说清楚吗?

编辑

http://www.albahari.com/threading/part2.aspx

enter image description here

最佳答案

Thread.SleepMonitor.Wait 都将线程放在the WaitSleepJoin state 中:

WaitSleepJoin: The thread is blocked. This could be the result of calling Thread::Sleep or Thread::Join, of requesting a lock — for example, by calling Monitor::Enter or Monitor::Wait — or of waiting on a thread synchronization object such as ManualResetEvent.

RegisteredWaitHandle是通过调用RegisterWaitForSingleObject获得的并传递一个 WaitHandle。通常此类的所有后代都使用阻塞机制,因此调用 Wait 会再次将线程放入 WaitSleepJoin(例如 AutoResetEvent)。

这是来自 MSDN 的另一段引述:

The RegisterWaitForSingleObject method checks the current state of the specified object's WaitHandle. If the object's state is unsignaled, the method registers a wait operation. The wait operation is performed by a thread from the thread pool. The delegate is executed by a worker thread when the object's state becomes signaled or the time-out interval elapses.

因此池中的线程确实在等待信号。

关于c# - Thread.sleep vs Monitor.Wait vs RegisteredWaitHandle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381771/

相关文章:

c - 相同的多线程代码在不同处理器上的时间差异?

c# - 不明白 Monitor.Pulse() 的必要性

c# - ASP.Net Core 3 远程证书在 MacOs 上无效

c# - 从外部 URL 中提取文本

java - 当我在单独的线程(实现 Runnable)上运行该类时,为什么会得到 "android.os.NetworkOnMainThreadException"?

c# - 类变量是 UML 聚合吗?

c# - 为什么 Type 类不在 System.Reflection 命名空间中?

C# 程序不评估操作并返回错误答案

c# - 在 asp.net core 中将 index.html 设置为默认页面

c# - 配置FluentNHibernate、FluentMappings.AddFromAssembly;意义