forked from vrcx-team/VRCX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CpuMonitor.cs
89 lines (80 loc) · 2.04 KB
/
CpuMonitor.cs
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
// Copyright(c) 2019 pypy. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
using System.Diagnostics;
using System.Threading;
namespace VRCX
{
public class CpuMonitor
{
public static readonly CpuMonitor Instance;
public float CpuUsage;
private PerformanceCounter _performanceCounter;
private Timer _timer;
static CpuMonitor()
{
Instance = new CpuMonitor();
}
public CpuMonitor()
{
try
{
_performanceCounter = new PerformanceCounter(
"Processor Information",
"% Processor Utility",
"_Total",
true
);
}
catch
{
}
// fallback
if (_performanceCounter == null)
{
try
{
_performanceCounter = new PerformanceCounter(
"Processor",
"% Processor Time",
"_Total",
true
);
}
catch
{
}
}
_timer = new Timer(TimerCallback, null, -1, -1);
}
internal void Init()
{
_timer.Change(1000, 1000);
}
internal void Exit()
{
lock (this)
{
_timer.Change(-1, -1);
_performanceCounter?.Dispose();
}
}
private void TimerCallback(object state)
{
lock (this)
{
try
{
if (_performanceCounter != null)
{
CpuUsage = _performanceCounter.NextValue();
}
}
catch
{
}
}
}
}
}