SystemMonitorClass.cs 932 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. public class SystemMonitor
  5. {
  6. private readonly PerformanceCounter _cpuCounter;
  7. private readonly PerformanceCounter _ramCounter;
  8. Stopwatch stopwatch = Stopwatch.StartNew();
  9. private float HisCPUCounter = 0;
  10. public SystemMonitor()
  11. {
  12. _cpuCounter = new PerformanceCounter(
  13. "Processor", "% Processor Time", "_Total");
  14. _ramCounter = new PerformanceCounter(
  15. "Memory", "Available MBytes");
  16. }
  17. public float GetCpuUsage()
  18. {
  19. stopwatch.Stop();
  20. if (stopwatch.ElapsedMilliseconds > 1000)
  21. {
  22. stopwatch.Restart();
  23. HisCPUCounter = _cpuCounter.NextValue();
  24. }
  25. else
  26. {
  27. stopwatch.Start();
  28. }
  29. return HisCPUCounter;
  30. }
  31. public float GetAvailableMemory()
  32. {
  33. return _ramCounter.NextValue();
  34. }
  35. }