Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between finalize and dispose in .net? [duplicate]

Possible Duplicate:
Finalize vs Dispose

Hi,

Recently I was quizzed in an interview about finalize and dispose. When is each one of them used and how is Garbage Collector related to them. Kindly share links to enlighten more on the topic.

Kindly share ...

Thanks in advance.

like image 326
HotTester Avatar asked Sep 05 '10 08:09

HotTester


2 Answers

Finalizers are run by the Garbage Collection before an object that is eligible for collection is reclaimed. Dispose() is meant for cleaning up unmanaged resources, like network connections, files, handles to OS stuff, &c. It works best in conjunction with the using block where the compiler makes sure that Dispose() will be called immediately once you are done with an object – and also ensures that you cannot work with the object anymore once it's disposed.

Note that finalizers don't have to run, so relying on that can be dangerous:

What this means for you: Your programs cannot rely on finalizers keeping things tidy. Finalizers are a safety net, not a primary means for resource reclamation. When you are finished with a resource, you need to release it by calling Close or Disconnect or whatever cleanup method is available on the object. (The IDisposable interface codifies this convention.)

Careful also with the precise time when an object becomes eligible for collection. Read the article linked above – it's neither scope (a weird word which has noting to do with the lifetime of an object – it's “the region of program text in which it is legal to refer to [a named entity] by its unqualified name.”) nor is it strictly reference counting as an object can become eligible for collection even before the last reference to it goes away.

like image 128
Joey Avatar answered Sep 22 '22 13:09

Joey


  1. Finalize: undeterministic nondeterministic destructor/finalizer called automatically by the Garbage Collector when there are no more references to this instance.
  2. Dispose: deterministically called by the developer on an object implementing IDisposable to free resources.
like image 21
Darin Dimitrov Avatar answered Sep 19 '22 13:09

Darin Dimitrov