0

I have a large object I would like to store in session, maybe a minute to use, and than remove it from memory. How long does an object stay in Gen0, Gen1 before it stays in Gen2 until GC? If I NULL it after a minute will the memory be cleared right away or at least in Gen0 or Gen1? I would like to free up that memory as fast as possible so it doesnt go to Gen2.

Session["Object"] = null;
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

1 Answers1

0

Looks like it is not deterministic, since it is optimized.

https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals

But here is how you can force it:

How to force garbage collector to run?

System.GC.Collect();

Bandi
  • 66
  • 4
  • `System.GC.Collect();` does not mean it will run immediately. – SᴇM May 26 '21 at 13:06
  • @SᴇM could you elaborate, I only found data it will not necessarily clean up everything. – Bandi May 26 '21 at 13:15
  • `Collect()` will message CLR to start collection, but that does not mean it will start immediately after that line. – SᴇM May 26 '21 at 13:17
  • 1
    I'm not sure that setting null to the session object and force GC.Collect will release it since it may still be referenced elsewhere. – Augusto Ferbonink May 26 '21 at 13:20
  • When you say start collection, does it mean Gen0 or Gen2? Does it mean only the session object or all objects? – Mike Flynn May 26 '21 at 13:20
  • @Mikr Flynn, calling GC.Collect without parameters will clean all generations. But it have other overloads if you want to clean an específic generation: https://learn.microsoft.com/pt-br/dotnet/api/system.gc.collect?view=net-5.0 – Augusto Ferbonink May 26 '21 at 13:22