本文介绍了是什么Thread.sleep代码(超时)和ManualResetEvent.Wait(超时)之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个Thread.sleep代码(超时)和resetEvent.Wait(超时)导致执行暂停至少暂停毫秒,所以它们之间有区别吗?我知道了Thread.Sleep导致线程放弃其时间片的剩余部分,​​从而可能导致,持续更长的时间比要求的睡眠。难道一个ManualResetEvent的对象的等待(超时)方法有同样的问题。

Both Thread.Sleep(timeout) and resetEvent.Wait(timeout) cause execution to pause for at least timeout milliseconds, so is there a difference between them? I know that Thread.Sleep causes the thread to give up the remainder of its time slice, thus possibly resulting in a sleep that lasts far longer than asked for. Does the Wait(timeout) method of a ManualResetEvent object have the same problem?

修改:我知道,一个ManualResetEvent的主要观点是从另一个线程的信号 - 现在我只关注事件的wait方法与指定超时时间,并没有其他主叫方设置事件的情况。我想知道它是否是更可靠的唤醒的时间超过了Thread.Sleep

Edit: I'm aware that a ManualResetEvent's main point is to be signaled from another thread - right now I'm only concerned with the case of an event's Wait method with a timeout specified, and no other callers setting the event. I want to know whether it's more reliable to awaken on-time than Thread.Sleep

推荐答案

主题。睡眠(超时)导致无条件等待恢复执行之前。 resetEvent.WaitOne(超时)导致线程等待是(1)事件被触发,直到,或达到(2)的超时时间。

Thread.Sleep(timeout) causes an unconditional wait before execution is resumed. resetEvent.WaitOne(timeout) causes the thread to wait until either (1) the event is triggered, or (2) the timeout is reached.

使用事件的关键是从另一个线程触发它们,所以当线程被唤醒,你可以直接控制。如果你不需要这些,你不应该使用的事件对象

The point of using events is to trigger them from another thread, so you can directly control when the thread wakes up. If you don't need this, you shouldn't be using event objects.

编辑:定时明智的,他们都是同样可靠。然而,你对唤醒时间的评论让我担心。为什么你需要你的代码按时醒来? 睡眠的WaitOne 并没有真正的设计精确一点。

Timing-wise, they are both equally reliable. However, your comment about "awakening on time" worries me. Why do you need your code to wake up on time? Sleep and WaitOne aren't really designed with precision in mind.

只有当暂停低于50毫秒左右,你所需要的可靠性,你应该看看时机的替代方法。 看起来像一个相当不错的概述。

Only if timeout is below 50ms or so and you need the reliability, you should look into alternate methods of timing. This article looks like a pretty good overview.

这篇关于是什么Thread.sleep代码(超时)和ManualResetEvent.Wait(超时)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:37