RegisterWaitForSingleObject 与 System.Timers

RegisterWaitForSingleObject vs System.Timers

我需要在等待特定时间后执行我的代码。这应该异步发生而不会阻塞我的线程。我在网上搜索并找到了很多方法来做到这一点。两个选项是使用 System.Timers 或使用 RegisterWaitForSingleObject 和 ManualResetEvent。

我无法真正弄清楚区别或何时更喜欢一个。 您能简要地告诉我为什么以及何时将 Timers 或 RegisterWaitForSingleObject 与 ManualResetEvent 一起使用吗?

旁注:我喜欢 TAP 和 TPL,并且通常比其他模式更喜欢它们(但这是不使用 System.Timer 的唯一原因吗?)

您使用 WaitForSingleObject 等待对象被告知处于特定状态。或发生超时。所以这不是你想要做的。您希望您的代码在特定时间内为 "paused"。所以"time"这里是主要结果。

我会尝试使用 await Task.Delay(ms)。这看起来是当今最方便的方法。

定时器

当您希望同一代码多次 运行 时使用 Timers,中间有特定的时间长度。

RegisterWaitForSingleObject

The documentation 说得最好:

Registers a delegate that is waiting for a WaitHandle.

当你想

时使用WaitHandle

wait for exclusive access to shared resources.

如果您不是在等待共享资源,那么它不适合您的用例。

手动重置事件

The documentation

Represents a thread synchronization event that, when signaled, must be reset manually.

"signalling" 和 "resetting" 是您的代码需要做的事情。当您的一个线程需要向另一个线程发出可以继续的信号时使用它。

您的用例

你说:

I need my code to execute after waiting for a specific time.

如果你不需要一遍又一遍地重复代码,不等待共享资源,不等待另一个线程,那么none上面的方法是合适的.

如果您真的只需要等待特定的时间再继续,那么,如前所述,使用 Task.Delay:

await Task.Delay(5000); //wait 5 seconds