c# – Dispose , Finalize , Destructor and GC class difference

Question:

I tried my luck in Google on this topic and finally got stuck.

  1. I'll start with GC – earlier in Schildt I read that the garbage collector cannot be called, that it is started automatically by the environment itself and nothing can be done about it, but I found such a GC.Collect() method, which, according to the description, launches the garbage collector. And the GC class itself also allows them to be controlled. So after all it turns out that it can be called manually? Or are there some subtleties and nuances?

  2. Enlighten what is actually the difference between Dispose и Finalize ? Which of them works with managed resources and what with unmanaged resources? And what is the essence of the implementation of the IDisposable interface (after all, in fact, everything can be done in the destructor)? As far as I understand, the destructor and Dispose do the same thing. If not, then what does the destructor do (earlier I read that the destructor describes the steps that the program must take when the object is destroyed, but Dispose essentially does the same thing).

  3. From all of the above, it becomes completely unclear what Finalize does then. Explain please.

Answer:

  1. Can. But it's rarely needed.
  2. They don't have much in common. Dispose is needed to release resources "here and now" (not really. Calling Dispose signals that you want to release the resource, but not the fact that this will definitely happen right there). The necessity and advantage of the IDisposable interface lies precisely in the fact that its implementation allows you to release resources not when the garbage collector gets to them, but when the programmer needs it. Resources can be expensive, and keeping them in memory indefinitely can be wasteful. There are no destructors in C# at all. There are finalizers. The difference is that the timing of the finalizer call is undefined. It's also worth noting that if Dispose is intended to be called manually, then the finalizer cannot be called manually. This is done automatically.
  3. Finalize is executed before the object is destroyed. We can say that this is the "last chance" to release resources correctly. It can also be considered that Finalize is the "last will of a dying" object. Defining this method only makes sense if the class has access to any unmanaged resources.
Scroll to Top
AllEscort