C# 如何创建WaitableTimer回调?
我正在尝试创建一个周期性的计时器,例如30分钟的C#,它能够将计算机从睡眠中唤醒并进行一些工作 似乎在网络上做了一些研究之后,应该使用Waitable timer函数。 我已经做了一些测试代码,但它并没有像我希望的那样工作。在调试和单步执行代码时,可以创建计时器并多次调用回调。但是,当我在没有任何断点的情况下运行代码时,回调只会被调用几次 我制作了一个表单应用程序,在按下按钮时运行“testWaitableTimer”。“myTimerEvent”应该打印每个计时器事件的时间。 我不想在测试时等待30分钟超时,因此该时间段设置为2秒间隔,到期时间为5秒C# 如何创建WaitableTimer回调?,c#,C#,我正在尝试创建一个周期性的计时器,例如30分钟的C#,它能够将计算机从睡眠中唤醒并进行一些工作 似乎在网络上做了一些研究之后,应该使用Waitable timer函数。 我已经做了一些测试代码,但它并没有像我希望的那样工作。在调试和单步执行代码时,可以创建计时器并多次调用回调。但是,当我在没有任何断点的情况下运行代码时,回调只会被调用几次 我制作了一个表单应用程序,在按下按钮时运行“testWaitableTimer”。“myTimerEvent”应该打印每个计时器事件的时间。 我不想在测试时等
public void myTimerEvent(IntPtr complretionArg, UInt32 timerLow, UInt32 timerHigh)
{
SetText( DateTime.Now.ToString() + "hepp ");
}
public delegate void TimerCompleteDelegate(IntPtr complretionArg,
UInt32 timerLow, UInt32 timerHigh);
[DllImport("kernel32.dll")]
public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, TimerCompleteDelegate pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume);
SafeWaitHandle handle;
private void testWaitableTimer()
{
DateTime utc = DateTime.Now.AddSeconds(5);
long duetime = utc.ToFileTime();
using (handle = CreateWaitableTimer(IntPtr.Zero, true, "MyWaitabletimer"))
{
// create a periodic timer that will fire of the first event after 5sec and then every 2 sec
if (SetWaitableTimer(handle, ref duetime, 2000, myTimerEvent, IntPtr.Zero, true))
{
using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset))
{
wh.SafeWaitHandle = handle;
wh.WaitOne(); // wait for first event
System.Threading.Thread.Sleep(2000);
wh.WaitOne(); // wait for second event
System.Threading.Thread.Sleep(500);
wh.WaitOne(); // wait for third event.
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
我是C#的新手,有一些问题: