0

I am trying to figure out what exactly increases the memory consumption with each iteration:

ManagementObjectSearcher Win32_Process = new ManagementObjectSearcher("Select * From Win32_Process");

while (true)
{
    foreach (ManagementObject PS in Win32_Process.Get()) { }

    //Not using the garbage collector GC.Collect()

    Thread.Sleep(1000);
}

Look at graph of used memory:

enter image description here enter image description here

I was convinced that the auto garbage collector cleared memory after cycles. Why is this not happening? How to avoid memory expansion without using GC.Collect()? Thanks

  • Does it keep increasing **forever**? – Lasse V. Karlsen Apr 07 '20 at 15:28
  • Garbage collection occurs as needed, not at deterministic points, like exiting a scope. – 500 - Internal Server Error Apr 07 '20 at 15:31
  • The garbage collector will collect the garbage when it needs to and when references to an object are released. Since you're in a `while (true)` loop, and don't seem to have anything that breaks out of it, there seems to be no reason for the GC to collect `Win32_Process` at least. – Heretic Monkey Apr 07 '20 at 15:32
  • 1
    The garbage collector is called to object that is not in use anymore and it looks like you calling the `ManagementObject .Get()` which imply that the object is in use – styx Apr 07 '20 at 15:32
  • 2
    Does this answer your question? [Understanding garbage collection in .NET](https://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net) or [Best Practice for Forcing Garbage Collection in C#](https://stackoverflow.com/q/233596/215552) – Heretic Monkey Apr 07 '20 at 15:33

1 Answers1

2

was convinced that the auto garbage collector cleared memory after cycles.

Why? The manual says opposite.

Why is this not happening?

Because there is no need. The GC runs when it is needed, not after every cycle (whatever this is).

How to avoid memory expansion without using GC.Collect()?

You do not. Or, you do - program in a way that leaves as little garbage as possible that longer term.

In your particular case it also helps to not ignore that this is an IDisposable object and you do not dispose it. All COM objects are IDisposable. WIthout disposing it there is a good chance you loose memory that the GC does not see, so it does not trigger a GC.

TomTom
  • 61,059
  • 10
  • 88
  • 148