cleanup code

This commit is contained in:
pypy
2020-11-01 23:41:21 +09:00
parent 2cc00465ad
commit c051dccecf
10 changed files with 241 additions and 207 deletions
+54 -38
View File
@@ -8,62 +8,78 @@ using System.Threading;
namespace VRCX
{
public static class CpuMonitor
public class CpuMonitor
{
public static float CpuUsage { get; private set; }
private static Thread m_Thread;
public static CpuMonitor Instance { get; private set; }
public float CpuUsage { get; private set; }
private readonly PerformanceCounter m_Counter;
private Thread m_Thread;
public static void Init()
static CpuMonitor()
{
m_Thread = new Thread(() =>
Instance = new CpuMonitor();
}
public CpuMonitor()
{
try
{
m_Counter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
}
catch
{
}
// fallback
if (m_Counter == null)
{
PerformanceCounter counter = null;
try
{
counter = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total", true);
m_Counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
}
catch
{
}
try
{
if (counter == null)
{
counter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
}
}
catch
{
}
if (counter != null)
{
while (m_Thread != null)
{
try
{
Thread.Sleep(1000);
}
catch
{
// ThreadInterruptedException
}
CpuUsage = counter.NextValue();
}
counter.Dispose();
}
})
}
m_Thread = new Thread(ThreadLoop)
{
IsBackground = true
};
}
internal void Init()
{
m_Thread.Start();
}
public static void Exit()
internal void Exit()
{
var T = m_Thread;
var thread = m_Thread;
m_Thread = null;
T.Interrupt();
T.Join();
thread.Interrupt();
thread.Join();
m_Counter?.Dispose();
}
private void ThreadLoop()
{
while (m_Thread != null)
{
if (m_Counter != null)
{
CpuUsage = m_Counter.NextValue();
}
try
{
Thread.Sleep(1000);
}
catch
{
// ThreadInterruptedException
}
}
}
}
}