Why does GetThreadTimes return

我们两清 提交于 2019-12-03 17:28:42

After making a couple simple mods to your code based on the link provided by Hans, valid times are displayed.

Adding a few interop declarations:

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
    IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle,
    uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);

[Flags]
public enum DuplicateOptions : uint
{
    DUPLICATE_CLOSE_SOURCE = (0x00000001), // Closes the source handle. This occurs regardless of any error status returned.
    DUPLICATE_SAME_ACCESS = (0x00000002),  // Ignores the dwDesiredAccess parameter. The duplicate handle has the same access as the source handle.
}

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();

then modifying how the handle is assigned:

//_threadHandle = GetCurrentThread();       <-- previous assignment
IntPtr processHandle = GetCurrentProcess();
bool result = DuplicateHandle(processHandle, GetCurrentThread(), processHandle, out _threadHandle, 0, false, (uint) DuplicateOptions.DUPLICATE_SAME_ACCESS);

produces the following result:

Starting...
Kernel time: 0
User time: 10000000
Combined raw execution time: 10000000
Elapsed thread time: 1000 milliseconds
Wall Clock Time: 1006 milliseconds
Kernel time: 0
User time: 20000000
Combined raw execution time: 20000000
Elapsed thread time: 2000 milliseconds
Wall Clock Time: 2004 milliseconds
Kernel time: 0
User time: 30000000
Combined raw execution time: 30000000
Ended.
Elapsed thread time: 3000 milliseconds
Wall Clock Time: 3045 milliseconds

EDIT:

Recently a great deal of effort has been given to handling too many threads that are created for a given system. Let's say you have a quad processor, and 20+ threads all want to run. Threads have a fairly large cost with respect to startup, kernel management, memory (they have their own stack), etc. The system may actually be slower (juggling contexts and scheduling) than if the thread count were to be reduced. So in .NET, libraries like TPL were created (allowing the developer to manage tasks, not threads). This allows the CLR to balance the appropriate thread count to the target system. But in your case (where you explicitly create a managed thread), there is nearly always a 1 to 1 relationship with native threads.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!