czw
2025-07-01 0c8543b3b66ce1f70a757137a803c0378b8c2286
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace HH.WCS.QingXigongchang.util
{
    internal class Monnn
    {
        private static readonly Dictionary<int, ThreadCpuUsage> _threadUsages = new Dictionary<int, ThreadCpuUsage>();
        private static readonly Process _currentProcess = Process.GetCurrentProcess();
        private static TimeSpan _previousTotalProcessorTime;
        private static DateTime _lastUpdateTime;
 
        public static void StartMonitoring()
        {
            _previousTotalProcessorTime = _currentProcess.TotalProcessorTime;
            _lastUpdateTime = DateTime.UtcNow;
 
            UpdateThreadCpuUsage();
            PrintThreadCpuUsage();
            //var timer = new Timer(_ =>
            //{
            //    UpdateThreadCpuUsage();
            //    PrintThreadCpuUsage();
            //}, null, 0, samplingIntervalMs);
        }
 
        private static void UpdateThreadCpuUsage()
        {
            var currentTime = DateTime.UtcNow;
            var timeElapsed = (currentTime - _lastUpdateTime).TotalSeconds;
            _lastUpdateTime = currentTime;
 
            var currentTotalProcessorTime = _currentProcess.TotalProcessorTime;
            var totalCpuUsed = (currentTotalProcessorTime - _previousTotalProcessorTime).TotalMilliseconds;
            _previousTotalProcessorTime = currentTotalProcessorTime;
 
            // 计算总可用CPU时间(考虑多核)
            var totalAvailableCpuTime = timeElapsed * 1000 * Environment.ProcessorCount;
 
            foreach (ProcessThread thread in _currentProcess.Threads)
            {
                try
                {
                    if (!_threadUsages.TryGetValue(thread.Id, out var usage))
                    {
                        usage = new ThreadCpuUsage(thread.Id);
                        _threadUsages[thread.Id] = usage;
                    }
 
                    var currentThreadTime = thread.TotalProcessorTime;
                    var threadCpuUsed = (currentThreadTime - usage.PreviousProcessorTime).TotalMilliseconds;
                    usage.PreviousProcessorTime = currentThreadTime;
 
                    // 计算CPU使用率百分比
                    usage.CpuUsagePercentage = (threadCpuUsed / totalAvailableCpuTime) * 100;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"无法监控线程 {thread.Id}: {ex.Message}");
                }
            }
        }
 
        private static void PrintThreadCpuUsage()
        {
            Console.Clear();
            Console.WriteLine($"进程ID: {_currentProcess.Id} 名称: {_currentProcess.ProcessName}");
            Console.WriteLine($"总CPU使用率: {_currentProcess.TotalProcessorTime.TotalMilliseconds}ms");
            Console.WriteLine("线程CPU使用情况:");
            Console.WriteLine("--------------------------------------------------");
            Console.WriteLine("ThreadID\tCPU Usage %\tThread State");
 
            foreach (var usage in _threadUsages.Values.OrderByDescending(u => u.CpuUsagePercentage))
            {
                Console.WriteLine($"{usage.ThreadId}\t\t{usage.CpuUsagePercentage:F2}%\t\t{GetThreadState(usage.ThreadId)}");
            }
        }
 
        private static string GetThreadState(int threadId)
        {
            try
            {
                return _currentProcess.Threads.Cast<ProcessThread>()
                    .FirstOrDefault(t => t.Id == threadId)?.ThreadState.ToString() ?? "Unknown";
            }
            catch
            {
                return "Unknown";
            }
        }
 
        private class ThreadCpuUsage
        {
            public int ThreadId { get; }
            public TimeSpan PreviousProcessorTime { get; set; }
            public double CpuUsagePercentage { get; set; }
 
            public ThreadCpuUsage(int threadId)
            {
                ThreadId = threadId;
            }
        }
    }
}