18 using System.Threading;
19 using System.Reflection;
21 using System.Diagnostics;
22 using System.Collections.Generic;
31 public static class OS
36 private static CpuPerformance CpuPerformanceCounter;
45 var p = (int)Environment.OSVersion.Platform;
46 return (p == 4) || (p == 6) || (p == 128);
58 public static string PathSeparation => Path.DirectorySeparatorChar.ToStringInvariant();
68 return d.AvailableFreeSpace / (1024 * 1024);
80 return (d.TotalSize - d.AvailableFreeSpace) / (1024 * 1024);
92 return d.TotalSize / (1024 * 1024);
100 private static DriveInfo GetDrive()
102 var assembly = Assembly.GetExecutingAssembly();
103 var drive = Path.GetPathRoot(assembly.Location);
104 return new DriveInfo(drive);
114 var proc = Process.GetCurrentProcess();
115 return proc.PrivateMemorySize64 / (1024 * 1024);
131 if(CpuPerformanceCounter !=
null)
133 return (decimal)CpuPerformanceCounter.CpuPercentage;
144 return new Dictionary<string, string>
159 CpuPerformanceCounter =
new CpuPerformance();
167 CpuPerformanceCounter.DisposeSafely();
173 private class CpuPerformance : IDisposable
175 private readonly CancellationTokenSource _cancellationToken;
176 private readonly Thread _cpuThread;
182 public float CpuPercentage {
get;
private set; }
187 public CpuPerformance()
189 _cancellationToken =
new CancellationTokenSource();
190 _cpuThread =
new Thread(CalculateCpu) { IsBackground =
true, Name =
"CpuPerformance" };
197 private void CalculateCpu()
199 var process = Process.GetCurrentProcess();
200 while (!_cancellationToken.IsCancellationRequested)
202 var startTime = DateTime.UtcNow;
203 var startCpuUsage = process.TotalProcessorTime;
205 if (_cancellationToken.Token.WaitHandle.WaitOne(startTime.GetSecondUnevenWait(5000)))
210 var endTime = DateTime.UtcNow;
211 var endCpuUsage = process.TotalProcessorTime;
213 var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
214 var totalMsPassed = (endTime - startTime).TotalMilliseconds;
215 var cpuUsageTotal = cpuUsedMs / totalMsPassed;
217 CpuPercentage = (float)cpuUsageTotal * 100;
226 _cpuThread.StopSafely(TimeSpan.FromSeconds(5), _cancellationToken);
227 _cancellationToken.DisposeSafely();