为什么调用GetThreadTimes时会出现“句柄无效”的错误?

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

这是我写的一个testing程序的肉:

#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: %d\n", 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); ... 

我得到以下debugging输出:

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

为什么是这样? 我们知道线程正在运行,因为“Thread Started!” 跟踪消息。 我已经尝试调整睡眠时间,直到线程终止。 我仍然得到无效的句柄错误。

testing程序是使用Visual C ++ 6构build的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);