You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中如何获取当前托管线程的CPU使用率

获取当前托管线程对应的ProcessThread

要关联System.Threading.Thread.CurrentThread和对应的System.Diagnostics.ProcessThread,核心是通过系统线程ID匹配——托管线程和系统线程是一一绑定的,但.NET没有直接提供映射API,需要借助Windows原生API获取当前线程的系统ID,再从当前进程的线程列表中匹配。

具体实现步骤

  1. 引入Windows原生API获取系统线程ID
    托管线程的ManagedThreadId是.NET Runtime分配的内部ID,和系统层面的线程ID不是同一个,所以需要调用GetCurrentThreadId()获取当前线程的系统ID:
using System.Runtime.InteropServices;

public static class ThreadHelper
{
    [DllImport("kernel32.dll")]
    private static extern uint GetCurrentThreadId();

    public static uint GetCurrentSystemThreadId()
    {
        return GetCurrentThreadId();
    }
}
  1. 从当前进程线程列表中匹配对应ProcessThread
    获取当前进程的所有系统线程,遍历找到ID与步骤1结果一致的ProcessThread:
using System.Diagnostics;
using System.Threading;

public static ProcessThread GetCurrentProcessThread()
{
    uint currentSystemThreadId = ThreadHelper.GetCurrentSystemThreadId();
    Process currentProcess = Process.GetCurrentProcess();

    foreach (ProcessThread thread in currentProcess.Threads)
    {
        if (thread.Id == currentSystemThreadId)
        {
            return thread;
        }
    }

    // 理论上不会走到这里,除非线程在遍历过程中终止
    return null;
}
  1. 使用示例
    拿到对应的ProcessThread后,就可以访问TotalProcessorTime属性:
ProcessThread currentProcessThread = GetCurrentProcessThread();
if (currentProcessThread != null)
{
    TimeSpan cpuTime = currentProcessThread.TotalProcessorTime;
    Console.WriteLine($"当前线程总CPU时间:{cpuTime}");
}

注意事项

  • 需要添加对System.Diagnostics程序集的引用。
  • 遍历线程列表时,可能存在线程已终止的情况,建议添加异常捕获逻辑。
  • 该方法仅适用于Windows平台,因为依赖Windows原生API。

内容的提问来源于stack exchange,提问作者uncaged

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:37:40