0

Is Dispose method automatically call the Finalize method internally? if yes How?

vivek
  • 45
  • 2

2 Answers2

2

The Dispose method does not call the finalizer automatically. Also, the finalizer does not automatically call the Dispose method.

See this question for more info:

How does the IDisposable interface work?

Community
  • 1
  • 1
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
2

Dispose and Finalize are different things. Neither ever invokes the other.

Odds are your class does not even need a finalizer. The only time you should ever build a finalizer is when you are building a class to work with a whole new kind of unmanaged resource. As an example, if you're building a database access class that will make use of the existing ADO.Net providers for Sql Server, MySql, etc, you do not need a finalizer. You should not build a finalizer, because the finalizer already written for the underlying providers will take care of the clean up for you. But if you're building the ADO.Net provider for a brand new kind of database, or re-implementing your provider from scratch without relying at all on the existing code, you should implement a finalizer.

So, to repeat:

Finalizers are only for types that originate unmanaged resources. They should only be implemented for a particular kind of resource once, and only ever called by the framework itself.

Dispose is for wrapping other types that expose unmanaged resources. It should be implemented every time you hold an unmanaged resource, and called for every instance of the class that is created.

Neither have anything at all to do with memory, ever, except perhaps memory held by unmanaged code.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • In "Implementing Finalize and Dispose to Clean Up Unmanaged Resources," http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx, it says, "Note that even when you provide explicit control using Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose." Looks to me like they're saying, "If you implement IDisposable, you should make your finalizer call Dispose(false)." – Jim Mischel Sep 13 '11 at 18:12
  • @Jim - Unfortunately, that page is poorly worded. All you really need to do is make sure the resource is cleaned up by a finalizer somewhere above your type in the inheritance chain, and it almost always already is. – Joel Coehoorn Sep 13 '11 at 18:15