How to resolve a memory leak caused by System.Diagnostics.PerformanceCounter

Summary

I wrote a process command line application that takes as parameters:

  • Process name or process identifier
  • Percentage of processor percentage.

What the program does is watch all processes with the given name or pid, and if their CPU usage exceeds the threshold value%, it kills them.

I have two classes: ProcessMonitorandProcessMonitorList

The first, wrapped around the System.Diagnostics.PerformanceCounter
last one is IEnumarablethat allows you to use the list structure of the first.

Problem

The program itself works great, however, if I look at the memory usage in the task manager, it grows in increments of about 20 kB per second. Note: the program checks the CPU counter PerformanceCounterevery second.

, , . (20-30).

PerfMon Heaps , , , , , , , :
Article

FxCop , .

: ", , ( ), , , , .

_pc = new PerformanceCounter("Process", "% Processor Time", processName);

, _pc ProcessMonitor.

, . .

public float NextValue()
{
        if (HasExited()) return PROCESS_ENDED;
        if (_pc != null)
        {
            _lastSample = _pc.NextValue();   //<-----------------------
            return _lastSample;
        }
        else return -1;
}

, NextValue(), System.Diagnostics.PerformanceCounter.

:

  • ?
  • , , ?
  • , , ?
+3
1

, , .
Reflector, System.Diagnostics.

, NextValue

GC.SuppressFinalization();

, ( , , , , ), Dispose() .

, , IDisposable , , PerformanceCounter.

IList<PerformanceMonitor> , voilà, .

, .

+4

Source: https://habr.com/ru/post/1755017/


All Articles