Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Who calls GC.Collect() in C#? is it a CLR?


What I have tried:

I have tried to find the working of GC.Collect() but I didnt find any good article. Please help to understand the caller of the GC.Collect()
Posted
Updated 22-Mar-17 20:31pm

Quote:
Who calls GC.Collect() in C#? is it a CLR?

It's you (your code) who calls GC.Collect(), I belive.

GC.Collect Method (System)[^]
When to call GC.Collect() – Rico Mariani's Performance Tidbits[^]
 
Share this answer
 
In effect, you do: it's just done behind the scenes.
When you create a new instance of a class, the space needs to be allocated on the heap. The allocation system looks for a suitable "chunk" of memory to use, and if it doesn't find one, it calls the garbage collector to try and free some up.
If you think about it, it's the only sensible time to do it - you need the memory, so that's when the time must be taken to find it!

That's why it's very important to use Dispose (or a using block) to ensure that precious resources are released: if you don't Dispose of a file stream when you are finished with it, then the file remains open until the app closes or the GC is called by you running out of memory - this is very often why people get "file in use" errors and can't work out what is using it!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900