Finalize method or Destructor

Finalize method or Destructor are synonyms. We create destructor by typing ~ (tilde sign) and class name. Use of destructor is to cleanup unamaged resources when Garbage collector runs. It is a good practice that your destructor calls Dispose method and provides it with false boolean value. Why with false value? Because First Dispose method is called by your code and provides second Dispose method with true value, meaning only managed code will be disposed of, and by providing Dispose of method with false method we ensure that garbage collector will not try to destroy of already disposed of objects.

Destructor can be called in two ways:

  1. When Garbage collector runs by itself
  2. When we invoke Garbage Collector by using GC.Collect()

Garbage Collector

Have you ever wondered how applications know how much memory to use, how is that memory distributed or who cleans up memory? All those operations are executed by the Garbage Collector.

What triggers Garbage collector?

  • Your system is low on physical memory.  Meaning your system has used up almost all of your RAM memory and will start to use page file.
  • 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.
  • Application is written to call the GC.Collect method.

Continue reading

© 2021 LearnC#WithDarko

Theme by Anders NorenUp ↑