gpt4 book ai didi

c# - WaitForSingleObject 立即发出信号

转载 作者:行者123 更新时间:2023-11-30 23:27:59 24 4
gpt4 key购买 nike

我正在尝试唤醒我的电脑以防它进入休眠模式。我在某个网站上找到了这个代码片段,但我在最后添加的 Messagebox 总是立即返回。

我还在我的系统中启用了电源选项中的唤醒定时器。

[DllImport("kernel32.dll")]
public static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes,
bool bManualReset, string lpTimerName);

[DllImport("kernel32.dll")]
public static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long
pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr
lpArgToCompletionRoutine, bool fResume);

[DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
public static extern Int32 WaitForSingleObject(IntPtr handle, uint
milliseconds);

static IntPtr handle;

private void SetWaitForWakeUpTime()
{
long duetime = 1200000000;
handle = CreateWaitableTimer(IntPtr.Zero, true, "MyWaitabletimer");
SetWaitableTimer(handle, ref duetime, 0, IntPtr.Zero, IntPtr.Zero, true);
uint INFINITE = 0xFFFFFFFF;
int ret = WaitForSingleObject(handle, INFINITE);
MessageBox.Show("wake up !");
}

我这样调用它:

private void buttonTest_Click(object sender, EventArgs e)
{
SetWaitForWakeUpTime();
}

理论上这应该只在 2 分钟后发出信号,对吧?为什么它会立即发出信号,我该如何更正它?

最佳答案

SetWaitableTimer() 可以在绝对时间和增量时间上触发。来自 MSDN 文章:

pDueTime [in]
The time after which the state of the timer is to be set to signaled, in 100 nanosecond intervals. Use the format described by the FILETIME structure. Positive values indicate absolute time. Be sure to use a UTC-based absolute time, as the system uses UTC-based time internally. Negative values indicate relative time. The actual timer accuracy depends on the capability of your hardware. For more information about UTC-based time, see System Time.

现在您使用了一个正值,所以您指定了 1600 年的日期,它总是立即完成。看起来您的实际意图是使用 2 分钟的间隔,因此您必须使用负值 -1200000000。

可能的真实意图是让它在时钟的特定时间醒来,给定使用场景,使用 DateTime.ToUniversalTime().ToFileTime()

关于c# - WaitForSingleObject 立即发出信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36205316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com