C# is a Garbage Collected language. The Garbage Collector allocates resources for you, and reclaims them when they are no longer used.
Unless you have a really good reason, you shouldn't be calling GC.Collect()
at all - the Garbage Collector is smart, and will only run when it thinks it needs to.
This can be triggered by a number of situations, as shown in the docs:
Garbage collection occurs when one of the following conditions is true:
The system has low physical memory. This is detected by either the low memory notification from the OS or low memory indicated by the host.
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
Importantly, Garbage Collection can cause all running threads to be paused so it can analyze all the objects in your heap to see if they're still needed at all. This takes time, and if you're running it frequently when it's not required, it can negatively affect the performance of your program.