-3
#include <windows.h>
#include <stdio.h>

TASK (Task2ms)
{
    printf("Hello"):

    SetEvent(Task1);
}

void main()
{
    int arg;
    HANDLE Task1;
    HANDLE HTimer1 =NULL;
    HANDLE HTimerQueue1 = NULL;
    Task1 = CreateEvent(NULL, TRUE, FALSE, NULL);
    if(NULL == Task1)
    {
        printf("CreateEvent failed (%d)\n", GetLastError());
        return 1;
    }

    //create a timer queue
    HTimerQueue1 = CreateTimerQueue();
    if(NULL == HTimerQueue1)
    {
        printf("CreateTimerQueue failed (%d)\n", GetLastError());
        return 2;
    }

    //phNewTimer - Pointer to a handle; this is an out value
    //TimerQueue - Timer queue handle. For the default timer queue, NULL
    //Callback - Pointer to the callback function
    //Parameter - Value passed to the callback function
    //DueTime - Time (milliseconds), before the timer is set to the signaled state for the first time 
    //Period - Timer period (milliseconds). If zero, timer is signaled only once
    //Flags - One or more of the next values (table taken from MSDN):

    //set the timer to call the timer routine in 2ms
    if(!CreateTimerQueueTimer( &HTimer1, HTimerQueue1, (WAITORTIMERCALLBACK)TASK, &arg, 2,0,0))
    {
        printf("CreateTimerQueueTimer failed (%d)\n", GetLastError());
        return 3;
    }

    //Do other work here

    printf("Call timer routine in 2 milliseconds...\n");
    // wait for the timeröqueue thread to complete using an event

    if (WaitForSingleObject(Task1, INFINITE) !=WAIT_OBJECT_0)
        printf("WaitForSingleObject failed (%d)\n", GetLastError());
    CloseHandle(Task1);

    //Delete all timers in the timer queue
    if(!DeleteTimerQueue(HTimerQueue1))
        printf("DeleteTimerQueue failed (%d)\n", GetLastError());

    return 0;
}

我创建了一个名为 Task(task 2ms) 的函数,它每 2ms 调用一次。所以我为此创建了一个计时器队列。如果我喜欢这样,那么每 2 毫秒就会调用一次任务函数。这是正确的吗?

4

1 回答 1

2

...每 2 毫秒调用一次。这是正确的吗?

不,这是不对的。

设置定时器队列定时器时,需要遵循文档:

您指定DueTime为 2 毫秒!

DueTime:在定时器第一次发出信号之前必须经过的相对于当前时间的时间量(以毫秒为单位)。

并且您将 指定Period为零!

定时器的周期,以毫秒为单位。如果此参数为零,则向计时器发出一次信号。如果此参数大于零,则计时器是周期性的。每次经过该周期时,周期性定时器会自动重新激活,直到定时器被取消。

您还必须指定Period为 2 ms。

但是您的代码无论如何都没有处理多个计时器事件。它只是在第一个计时器事件发生后结束。所以无论如何你可能不得不花更多的时间在代码上,例如:

while (1) {
  if (WaitForSingleObject(Task1, INFINITE) == WAIT_OBJECT_0) {
    printf("2 ms event occurred!\n");
  } else {
    printf("WaitForSingleObject failed (%d)\n", GetLastError());
    break;
  }
} 

PS:有什么Task2ms用?And:printf("Hello"):必须替换为printf("Hello\n");(使用分号作为终止符/语句分隔符!)。您实际上是在询问您从未尝试过编译的代码。你不应该期望人们热衷于回答这些问题。

于 2013-11-01T09:18:27.077 回答