public static async Task Start(int percent, CancellationToken cancellationToken) { ThreadPool.SetMaxThreads(MaxThreadCount, 2 * MaxThreadCount); ThreadPool.SetMinThreads(MinThreadCount, 2 * MinThreadCount); if (percent < 0 || percent > 100) { throw new InvalidOperationException("Percent must be in a diapazone [0..100]!"); } using (var cpuCounter = ProcessCpuCounter.GetPerfCounterForProcessId(Process.GetCurrentProcess().Id)) { while (/*!cancellationToken.IsCancellationRequested*/ true) { var cpuValue = cpuCounter.NextValue(); Console.WriteLine($"CPU USAGE: {cpuValue}: {percent}!"); if (cpuValue > percent) { Console.WriteLine($"CPU BOUNDS EXCEEDED: {cpuValue}: {percent}!"); while (_currentThreadCount > MinThreadCount && cpuValue > percent) { var delta = (int)(0.1 * _currentThreadCount); delta = delta > 1 ? delta : 1; _currentThreadCount -= delta; _currentThreadCount = _currentThreadCount > MinThreadCount ? _currentThreadCount : MinThreadCount; ThreadPool.SetMaxThreads(_currentThreadCount, 2 * _currentThreadCount); Thread.Sleep(500); cpuValue = cpuCounter.NextValue(); } } else if (cpuCounter.NextValue() < 0.5 * percent) { Console.WriteLine($"CPU IS UNDERUSED: {cpuValue}: {percent}!"); while (_currentThreadCount > MinThreadCount && cpuCounter.NextValue() < percent) { var delta = (int)(0.1 * _currentThreadCount); delta = delta > 1 ? delta : 1; _currentThreadCount += delta; _currentThreadCount = _currentThreadCount < MaxThreadCount ? _currentThreadCount : MaxThreadCount; ThreadPool.SetMaxThreads(_currentThreadCount, 2 * _currentThreadCount); Thread.Sleep(500); cpuValue = cpuCounter.NextValue(); } } Console.WriteLine($"CURRENT THREAD COUNT: {_currentThreadCount}"); Thread.Sleep(15000); } } }
internal UiProcess([JetBrains.Annotations.NotNull] Process process) { _process = process; try { Path = _process.MainModule.FileName; } catch (Exception) { Path = ""; } try { _cpuCounter = ProcessCpuCounter.GetPerfCounterForProcessId(_process.Id); _cpuCounter.NextValue(); } catch (Exception) { } }
private static void Main(string[] args) { var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Start"); var processCpuCounter = new ProcessCpuCounter(); if (!long.TryParse(ConfigurationManager.AppSettings["intervalMilliSecond"], out var intervalMilliSecond)) { intervalMilliSecond = 20 * 1000; } var applicationName = ConfigurationManager.AppSettings["Client"]; try { var rc = HostFactory.Run(x => { x.Service <MonitorService>(s => { s.ConstructUsing(name => new MonitorService(processCpuCounter, applicationName, intervalMilliSecond)); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Prototy application cpu monitor"); x.SetDisplayName("Cpu monitor"); x.SetDisplayName("CpuMonitorUsages"); }); var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); Environment.ExitCode = exitCode; } catch (Exception ex) { logger.Error(ex, "Error in start"); } logger.Info("Finish"); }