Having a garbage collected runtime removes one of the biggest sources of program errors, memory allocation errors. You no longer have to worry about freeing memory which you no longer use, and there is no risk that you use memory after it has been freed. Unfortunately, memory leaks are still a reality. A memory leak can occur if an instance is unintentionally being referenced from some other long-living instance, or from a static field. In this case the instance cannot be garbage collected. A very common unintentional reference is an event handler that is never removed.
.NET Memory Profiler can help you locate instances that are being referenced unintentionally, and it will tell you why the instance has not been garbage collected.
Additionally, the only resource the garbage collector is aware of is memory managed by the runtime. Unmanaged resources like file handles, database connections, bitmaps etc. are not handled well by the garbage collector. The runtime provides a mechanism called Finalization, which can be used to clean-up unmanaged resources. However, finalization is an expensive feature and the clean-up is not deterministic; the clean-up can happen any time after an instance is no longer reachable. To solve the problem with cleaning up unmanaged resources, the Dispose pattern was introduced. The Dispose pattern allows (or rather demands) the user to dispose the instance explicitly.
The dispose tracker feature of .NET Memory Profiler helps you to make sure that all disposable instances are correctly disposed.
Finally, to optimize the performance of the garbage collector, certain assumptions have been made on the way instances are allocated. If a program allocates memory in a way that is not suitable for the garbage collector, then performance of the garbage collector will suffer, and the memory overhead will be bigger.
By using the real-time view of .NET Memory Profiler, it is possible to get an understanding on how well the allocations in the program correspond with the assumptions made by the garbage collector.
Download .NET Memory Profiler to see how it can help you find memory leaks and optimize memory usage in your application.
Download Free Trial