如何创建WaitableTimer回调?

时间:2013-03-03 23:21:35

标签: c#

我正在尝试在C#中创建一个例如30分钟的定期计时器,它能够将计算机从睡眠状态唤醒并进行某些工作。

似乎应该在网上进行一些研究后使用Waitable计时器功能。 我已经制作了一些测试代码,但它不能像我希望的那样工作。可以创建计时器,当我调试并单步执行代码时,会多次调用回调。但是当我运行没有任何断点的代码时,回调只会被调用几次。

我在按下按钮时创建了一个运行“testWaitableTimer”的Form应用程序。 “myTimerEvent”应该打印每个计时器事件的时间。 我不想在测试时等待30分钟超时,因此周期设置为2秒间隔,到期时间为5秒。

    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#很陌生并且有一些问题:

  1. 运行代码时,多次调用wh.WaitOne(),但似乎只等待第一个定时器事件。如果删除所有“睡眠”功能,代码将等待第一个,然后跳过其余部分。

  2. 我在testfunction之外创建了safeWaitHandle。但似乎只在运行测试函数时才调用计时器回调。退出测试功能时停止执行。那是为什么?

0 个答案:

没有答案