为什么我在调用 GetThreadTimes 时收到错误"The handle is invalid"?

Why do I get the error "The handle is invalid" when invoking GetThreadTimes?

本文关键字:The handle is invalid 错误 调用 GetThreadTimes 为什么      更新时间:2023-10-16

我需要获取工作线程的CPU时间。看来我必须使用GetThreadTimes来做到这一点,因为我的目标是Windows XP和更新版本。根据文档,Windows XP不支持QueryThreadCycleTime。

这是我写的一个测试程序的要点:

#include <windows.h>
UINT TestFunction(LPVOID pParam)
{
    TRACE("Thread Started!n");
    Sleep(10000);
    TRACE("Thread about to terminate!n");
    return 0;
}
...
CWinThread* thread = AfxBeginThread(TestFunction, NULL);
Sleep(500);
LPFILETIME creationTime = NULL;
LPFILETIME exitTime = NULL;
LPFILETIME kernelTime = NULL;
LPFILETIME userTime = NULL;
int result = GetThreadTimes(thread, creationTime, exitTime, kernelTime, userTime);
TRACE("Result: %dn", result);
if(result != 0)
{
    TRACE("Got result!n");
}
else
{
    //ref: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680582(v=vs.85).aspx
    LPVOID lpMsgBuf;
    DWORD dw = GetLastError(); 
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL
    );
    TRACE("Timing query failed with error %d: %s", dw, lpMsgBuf);
    LocalFree(lpMsgBuf);
...

我得到以下调试输出:

Thread Started!
Result: 0
Timing query failed with error 6: The handle is invalid.

这是为什么呢?我们知道线程正在运行是因为"线程已启动!"跟踪消息。我尝试调整睡眠时间,直到线程终止。我仍然收到无效句柄错误。

测试程序是 Visual C++ 6 中内置的 MFC 应用程序。

你的thread是一个CWinThread *。传递给GetThreadTimes的参数应为HANDLE

CWinThread 有一个强制转换运算符来获取线程的操作系统句柄,因此您应该能够使用:GetThreadTimes(*thread, ...)

不过还有一个问题:你真的需要改变这些:

LPFILETIME creationTime = NULL;
LPFILETIME exitTime = NULL;
LPFILETIME kernelTime = NULL;
LPFILETIME userTime = NULL;

像这样:

FILETIME creationTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;

然后,当您调用该函数时,您传递每个函数的地址,因此您的调用如下所示:

GetThreadTimes(*thread, &creationTime, &exitTime, &kernelTime, &userTime);
相关文章: