.Net 多线程:睡眠、等待、中断、连接

发布于 2024-11-24 23:28:31 字数 115 浏览 1 评论 0原文

我对何时使用它们感到困惑。我知道所有这些方法都会造成线程阻塞。

那么他们的具体情况用法是什么。

另外,Wait() 的首选技术是什么..(仅在 ManualResetEvent 中?)

I get confused as in when to use them.. I know all of these methods make a thread block.

So what are their particular case usage.

Also what is preferred technique of Wait().. (as in ManualResetEvent ONLY?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲喜皆因你 2024-12-01 23:28:31

Sleep :我不建议使用它,除非它是一个进行持续轮询的后台线程,因为它可以掩盖竞争条件。为发送给它的参数的最小值生成时间片,操作系统中的时间片量子确定实际的粒度(可能比您告诉它的时间更长)

Wait :在 .NET 中,这是一个 spinwait,用于锁定。它将处理器置于一个小循环(通常是 2 个指令)中,基本上是一个阻塞线程但继续执行而不是产生其时间片的睡眠。或者可以是 WaitOne,它等待 WaitHandle 来接收信号。在这种情况下,线程等待指定的接收信号的时间,然后解除阻塞,或者您可以永远等待,直到接收到信号(可用于实现异步操作的超时,也有其他用途)

中断:中断处于等待、睡眠或连接阻塞状态的线程。

Join:将线程加入到当前上下文线程,并在加入的线程完成后解除阻塞,用于等待需要继续的事情完成

Sleep : I don't recommend the use of this unless it's a background thread that does constant polling as it can mask race conditions. Yields timeslice for a MINIMUM of the parameter sent to it, timeslicing quantums in the OS determine the actual granularity (which could be more time than you tell it)

Wait : In .NET this is a spinwait, used for locking. It puts the processor into a small loop (usually 2 instructions), basically a sleep that blocks the thread but continues executing insteading of yielding its timeslice. Alternatively could be WaitOne which waits on a WaitHandle to receive a signal. In this case the thread waits up to the amount of time specified for the signal to be received and then unblocks or you can wait forever until the signal is received (can be used to implement timeouts on async operations, also has other uses)

Interrupt : Interrupt a thread that is either in the wait, sleep or join blocking state.

Join: join the thread to the current context thread and unblocks once the joined thread finishes, used to wait for something to finish that is needed to continue

楠木可依 2024-12-01 23:28:31

有一本优秀的免费电子书,由 LINQPad 和几本 C# 畅销书的作者 Joseph Albahari 编写,内容为 C# 中的线程 。如果你付出一些努力来浏览这些材料,你的困惑就会消失......

There is an excelent free eBook by Joseph Albahari, author of LINQPad and several C# bestsellers, on Threading in C#. If you put some effort in going through that material your confusion should vanish...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文