Is there a difference between defining a destructor and not? - c#

Is there a difference in the garbage collection if I define the ~Example part or not?
class Example
{
public void Display()
{
Console.WriteLine("hi");
}
~Example()//**does giving this part or not has any effects in garbage collection**
{
}
}
and
class Example
{
public void Display()
{
Console.WriteLine("hi");
}
}

C# is a garbage collected language. This means that the .NET framework, in which code written in C# is executed, has a mechanism for the memory management. We don't have like in C++ to care about the destruction of the created objects, in order we don't have a high memory footprint or memory leaks. That's the job of Garbage Collector.
As it is stated more formally in MSDN
In general, C# does not require as much memory management as is needed
when you develop with a language that does not target a runtime with
garbage collection. This is because the .NET Framework garbage
collector implicitly manages the allocation and release of memory for
your objects. However, when your application encapsulates unmanaged
resources such as windows, files, and network connections, you should
use destructors to free those resources. When the object is eligible
for destruction, the garbage collector runs the Finalize method of the
object.
However the concept of destructors exist also in C# and as in other languages are used for the destruction of instances of classes. Furthermore a destructor cannot be called. It is invoked automatically.
For instance, if we declare the following class:
class Customer
{
~Customer()
{
// Here we place our clean up statements.
}
}
The destructor will implicitly call the Finalize method on the base class of the object. As it is explained in the above link this code would be translated to the following one by the C# compiler:
protected override void Finalize()
{
try
{
// Here goes our clean up statements.
}
finally
{
base.Finalize();
}
}
This means that the Finalize method is called recursively for all
instances in the inheritance chain, from the most-derived to the
least-derived.
In any case you should keep in mind the following:
The programmer has no control over when the destructor is called
because this is determined by the garbage collector. The garbage
collector checks for objects that are no longer being used by the
application. If it considers an object eligible for destruction, it
calls the destructor (if any) and reclaims the memory used to store
the object. Destructors are also called when the program exits.

If the destructor actually had some code in it that is executing, than yes, of course that would be a difference, however you can't guarantee the time when it would be called etc.
Also, you ask a question about asp.net, yet you post code from a console application?

C# has built in mechanism for freeing up un used objects or invalid objects. It runs periodically and cleans up the memory.
There is no need to write any explicit code/functionality to implement this.
For more details refer to this

Related

Why .NET Object has method Finalize()?

I know that Finalize method is used by garbage collector to let object free up unmanaged resources. And from what I know, Object.Finalize is never called directly by GC (object is added to f-reachable queue during it's construction if it's type overrides the Finalize method by implementing finalizer).
Object.Finalize is only called from autogenerated finalizer code:
try
{
//My class finalize implementation
}
finally
{
base.Finalize(); // Here chain of base calls will eventually reach Object.Finalize/
}
So having an arbitrary class, derived from Object, wouldn't call Object.Finalize - you need finalizer for Object.Finalize to make sense and for most classes it doesn't make sense and is unused (not saying it's implementation is empty in fact).
Would it be too complex to check existence of Finalize method in a class without it overriding Object.Finalize, and generating root finalizer without try{}finally{base.Finalize()} call? Something similar to Add method for collection initializing - you don't have to implement any interface or override that method - just implement public void Add(item) method.
It would complicate C# compiler a bit, but make finalizer run slightly faster by removing one redundant call, and most importantly - make Object class easier to understand without having protected Finalize method with empty implementation while it doesn't need to finalize anything.
Also it might be possible to implement FinalizableObject class, derived from Object and make compiler derive all classes which have finalizer from that. It could implement IDisposable and make the disposing pattern, recommended by Microsoft reusable without need to implement it in every class. Actually I'm surprised such base class doesn't exist.
Edit
The garbage collection does not call the child implementation of Object.Finalise unless the method is overridden. Why is it available to all objects? So that it can be overridden when needed but unless it is there is no performance impact. Looking at documentation here, it states;
The Object class provides no implementation for the Finalize method, and the garbage collector does not mark types derived from Object for finalization unless they override the Finalize method.
Notes on finalization
Quoting directly from Ben Watson's excellent book Writing High-Performance .NET Code as he explains far better than I ever could;
Never implement a finalizer unless it is required. Finalizers are code, triggered by the garbage collector to cleanup unmanaged resources. They are called from a single thread, one after the other, and only after the garbage collector declares the object dead after a collection. This means that if your class implements a finalizer, you are guaranteeing that it will stay in memory even after the collection that should have killed it. This decreases overall GC efficiency and ensures that your program will dedicate CPU resources to cleaning up your object.
If you do implement a finalizer, you must also implement the IDisposable
interface to enable explicit cleanup, and call GC.SuppressFinalize(this)
in the Dispose method to remove the object from the finalization queue.
As long as you call Dispose before the next collection, then it will clean up the object properly without the need for the finalizer to run. The following example correctly demonstrates this pattern;
class Foo : IDisposable
{
~Foo()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.managedResource.Dispose();
}
// Cleanup unmanaged resource
UnsafeClose(this.handle);
// If the base class is IDisposable object, make sure you call:
// base.Dispose();
}
}
Note Some people think that finalizers are guaranteed to run. This is generally true, but not absolutely so. If a program is force-terminated
then no more code runs and the process dies immediately. There is also a time limit to how long all of the finalizers are given on process shutdown. If your finalizer is at the end of the list, it may be skipped. Moreover,
because finalizers execute sequentially, if another finalizer has an infinite loop bug in it, then no finalizers after it will ever run. While finalizers are not run on a GC thread, they are triggered by a GC so if you have no collections, the finalizers will not run. Therefore, you should not rely on finalizers to clean up state external to your process.
Microsoft has a good write up on finalizers and the Disposable pattern here
The C# language destructor syntax obscures too much about what a finalizer really does. Perhaps best demonstrated with a sample program:
using System;
class Program {
static void Main(string[] args) {
var obj = new Example();
obj = null; // Avoid debugger extending its lifetime
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadLine();
}
}
class Base { ~Base() { Console.WriteLine("Base finalizer called"); } }
class Derived : Base { ~Derived() { Console.WriteLine("Derived finalizer called"); } }
class Example : Derived { }
Output:
Derived finalizer called
Base finalizer called
There are some noteworthy things about this behavior. The Example class itself does not have a finalizer, yet its base class finalizers are called anyway. That the Derived class finalizer is called before the Base class finalizer is not accidental. And note that the Derived class' finalizer has no call to base.Finalize(), even though the MSDN article for Object.Finalize() demands that it does, yet it is called anyway.
You may easily recognize this behavior, it is the way a virtual method behaves. One whose override calls the base method, like virtual method overrides commonly do. Which is otherwise exactly what it is inside the CLR, Finalize() is a plain virtual method like any other. The actual code generated by the C# compiler for the Derived class' destructor resembles this:
protected override Derived.Finalize() {
try {
Console.WriteLine("Derived finalizer called");
}
finally {
base.Finalize();
}
}
Not valid code, but the way it could be reverse-engineered from the MSIL. The C# syntax sugar ensures you can never forget to call the base finalizer and that it can't be aborted by a thread abort or AppDomain unload. The C# compiler does not otherwise help and auto-generate a finalizer for the Example class; the CLR does the necessary work of finding the finalizer of the most-derived class, traversing the method tables of the base classes until it finds one. And likewise helps in the class loader by setting a flag to indicate that Example has base classes with a finalizer so needs to be treated specially by the GC. The Base class finalizer calls Object.Finalize(), even though it doesn't do anything.
So key point is that Finalize() is actually a virtual method. It therefore needs a slot in the method table for Object so a derived class can override it. Whether it could have been done differently is pretty subjective. Certainly not easily and not without forcing every language implementation to special-case it.

Difference between finalizer and finally in C# [duplicate]

I am studying how garbage collector works in c#. I am confused over the use of Destructor, Dispose and Finalize methods.
As per my research and understandings, having a Destructor method within my class will tell the garbage collector to perform the garbage collection in the way mentioned in the destructor method which cannot be called explicitly on the instances of the class.
The Dispose method is meant to provide the user to control the garbage collection. The Finalize method frees the resources used by the class, but not the object itself.
I am not sure if I understand it the right way. Please clarify the doubts. Any further links or guides are welcome.
Destructor implicitly calls the Finalize method, they are technically the same. Dispose is available with objects that implement the IDisposable interface.
You may see : Destructors C# - MSDN
The destructor implicitly calls Finalize on the base class of the
object.
Example from the same link:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
The Destructor's code is implicitly translated to the following code:
protected override void Finalize()
{
try
{
// Cleanup statements...
}
finally
{
base.Finalize();
}
}
Your understanding for the Destructor is right:
From MSDN
The programmer has no control over when the destructor is called
because this is determined by the garbage collector. The garbage
collector checks for objects that are no longer being used by the
application. If it considers an object eligible for destruction, it
calls the destructor (if any) and reclaims the memory used to store
the object. Destructors are also called when the program exits. It is
possible to force garbage collection by calling Collect, but most of
the time, this should be avoided because it may create performance
issues.
In C# terms, a destructor and finalizer are basically interchangeable concepts, and should be used to release unmanaged resources when a type is collected, for example external handles. It is very rare that you need to write a finalizer.
The problem with that is that GC is non-deterministic, so the Dispose() method (via IDisposable) makes it possible to support deterministic cleanup. This is unrelated to garbage collection, and allows the caller to release any resources sooner. It is also suitable for use with managed resources (in addition to unmanaged), for example if you have a type that encapsulates (say) a database connection, you might want disposing of the type to release the connection too.

Constructors starting with the ~ in a class

In this example link ....
https://stackoverflow.com/a/19737565/2948523
I found some sections like,
~ImprovedClass()
~Inner()
Please help me out what are they ? why and how should I use them in code
class Inner
{
public Inner(IntPtr unkOuter)
{
}
~Inner()
{
}
}
public class ImprovedClass
{
// constructor
public ImprovedClass()
{
}
~ImprovedClass()
{
}
}
This is a Destructor Destructors
They are used to release resources that the object may still be holding onto even though it is no longer in use.
Those are called destructors which are calling automatically at the end of your class instance life on instance. You can write code here to release some resources which have been used by your object. Here are some remarks about destructors:
Destructors cannot be defined in structs.
They are only used with classes.
A class can only have one destructor
Destructors cannot be inherited or overloaded.
Destructors cannot be called. They are invoked automatically.
Here is some guide
http://msdn.microsoft.com/en-us/library/vstudio/66x5fx1b.aspx
~ mark is used for destructor not the constructor.
When you are using unmanaged resources such as handles and database
connections, you should ensure that they are held for the minimum
amount of time, using the principle of acquire late and release early.
In C++ releasing the resources is typically done in the destructor,
which is deterministically run at the point where the object is
deleted. The .NET runtime, however, uses a garbage collector (GC) to
clean up and reclaim the memory used by objects that are no longer
reachable; as this runs on a periodic basis it means that the point at
which your object is cleaned up is nondeterministic. The consequence
of this is that destructors do not exist for managed objects as there
is no deterministic place to run them.

C# object not destroyed when using COM/ATL interface in C++

Lately I was doing a little project that involved a DLL module (that was created with C#) and that I needed to use in my application (that was written in unmanaged C++) For this to work I was using ATL/COM.
I noticed that even though I'm using a _com_ptr_t in my C++ application for handling my core COM interface, C# object's destructor is called only when my application is closed.
Let me give you some source to make things a bit more clearer:
Some of my C# code:
[ComVisible(true)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITestCOM
{
[DispId(1)]
void Connect([In, MarshalAs(UnmanagedType.U2)] ushort value);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(ITestCOMEvents))]
public partial class TestCOM : ITestCOM
{
...
~TestCOM()
{
MessageBox.Show("DESTRUCTOR");
}
...
public void Connect(ushort value)
{
...
}
}
I'm creating the .tlb file using something like this:
"RegAsm.exe TestCOM.dll /tlb:Test.tlb /codebase"
In my C++ header I have:
#import "C:\...\mscorlib.tlb"
#import "......\TestCOM.tlb" named_guids exclude("ISupportErrorInfo")
#include <afxdisp.h>
#include <atlcom.h>
class Unit : public ::IDispEventSimpleImpl<0, Unit, &__uuidof(TestCOM::ITestCOMEvents)>
{
public:
BEGIN_SINK_MAP(Unit)
SINK_ENTRY_INFO(0, __uuidof(TestCOM::ITestCOMEvents), 0x1, OnEventCallback, &OnEventCallbackDef)
END_SINK_MAP()
...
private
TestCOM::ITestCOMPtr mTestCOM;
// NOTE: This would be the same as "_com_ptr_t<_com_IIID<TestCOM::ITestCOM, &__uuidof(TestCOM::ITestCOM)> > mTestCOM;"
}
And my C++ source file I create my "mTestCOM" like this:
mTestCOM.CreateInstance(TestCOM::CLSID_TestCOM)
And basically that's it.. I can use any of my C# "TestCOM" object's functions like this:
mTestCOM->Connect(7);
The question is:
Why my C# TestCOM object's destructor is called only when my application is closed, and not when my C++ "Unit" object is destroyed?
Though I'm not familiar with C# and COM integration, I do know that destructors in C# work very differently to destructors in C++. A C# object is memory-managed and garbage-collected. This means that at some point after the object stops being referenced by the application it belongs to and becomes 'unreachable', the garbage collector will destroy it.
So the first important thing is that the delay between an object being abandoned and the garbage collector destroying it is nondeterministic... it will happen "at some point in the future", which may well be at the point the application terminates.
Secondly, the garbage collector is not always running. There is the concept of "memory pressure", when your application is allocating large chunks of memory and the free memory available to it is running out... at that point, the garbage collector will fire to get rid of old, unreachable objects. If your application does not allocate lots of memory it will not suffer from any memory pressure and the garbage collector will not need to run.
If you want to deterministically clean up some of a managed object's resources, you will need to use something like the IDisposable interface and call the Dispose method explicitly.
This is entirely normal and a side-effect of the garbage collector. Which only collects garbage, and runs the finalizer, when a managed app allocates enough memory to fill up a generation and trigger a collection. If you don't allocate enough then this won't happen until the app terminates.
This should not be a problem, make sure that you don't use the finalizer to do anything other than release unmanaged resources that were not disposed. Writing a finalizer is the wrong thing to do in 99.9% of all cases, finalizers are implementation details of .NET framework classes. Like the SafeHandle classes. There is otherwise no way to let deterministic destruction in the client app produce deterministic disposal in the managed code. If you do need to dispose members then you'll need to expose a method that the client code can call.

Finalize vs Dispose

Why do some people use the Finalize method over the Dispose method?
In what situations would you use the Finalize method over the Dispose method and vice versa?
The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).
The Dispose method on the other hand is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.
The standard practice is to implement IDisposable and Dispose so that you can use your object in a using statment. Such as using(var foo = new MyObject()) { }. And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.
Others have already covered the difference between Dispose and Finalize (btw the Finalize method is still called a destructor in the language specification), so I'll just add a little about the scenarios where the Finalize method comes in handy.
Some types encapsulate disposable resources in a manner where it is easy to use and dispose of them in a single action. The general usage is often like this: open, read or write, close (Dispose). It fits very well with the using construct.
Others are a bit more difficult. WaitEventHandles for instances are not used like this as they are used to signal from one thread to another. The question then becomes who should call Dispose on these? As a safeguard types like these implement a Finalize method, which makes sure resources are disposed when the instance is no longer referenced by the application.
Finalize is the backstop method, called by the garbage collector when it reclaims an object. Dispose is the "deterministic cleanup" method, called by applications to release valuable native resources (window handles, database connections, etc.) when they are no longer needed, rather than leaving them held indefinitely until the GC gets round to the object.
As the user of an object, you always use Dispose. Finalize is for the GC.
As the implementer of a class, if you hold managed resources that ought to be disposed, you implement Dispose. If you hold native resources, you implement both Dispose and Finalize, and both call a common method that releases the native resources. These idioms are typically combined through a private Dispose(bool disposing) method, which Dispose calls with true, and Finalize calls with false. This method always frees native resources, then checks the disposing parameter, and if it is true it disposes managed resources and calls GC.SuppressFinalize.
Finalize gets called by the GC when this object is no longer in use.
Dispose is just a normal method which the user of this class can call to release any resources.
If user forgot to call Dispose and if the class have Finalize implemented then GC will make sure it gets called.
Finalize
Finalizers should always be protected, not public or private so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize method
Finalizers should release unmanaged resources only.
The framework does not guarantee that a finalizer will execute at all on any given instance.
Never allocate memory in finalizers or call virtual methods from finalizers.
Avoid synchronization and raising unhandled exceptions in the finalizers.
The execution order of finalizers is non-deterministic—in other words, you can't rely on another object still being available within your finalizer.
Do not define finalizers on value types.
Don't create empty destructors. In other words, you should never explicitly define a destructor unless your class needs to clean up unmanaged resources and if you do define one, it should do some work. If, later, you no longer need to clean up unmanaged resources in the destructor, remove it altogether.
Dispose
Implement IDisposable on every type that has a finalizer
Ensure that an object is made unusable after making a call to the Dispose method. In other words, avoid using an object after the Dispose method has been called on it.
Call Dispose on all IDisposable types once you are done with them
Allow Dispose to be called multiple times without raising errors.
Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
Avoid creating disposable value types
Avoid throwing exceptions from within Dispose methods
Dispose/Finalized Pattern
Microsoft recommends that you implement both Dispose and Finalize when working with unmanaged resources. The Finalize implementation would run and the resources would still be released when the object is garbage collected even if a developer neglected to call the Dispose method explicitly.
Cleanup the unmanaged resources in the Finalize method as well as Dispose method. Additionally call the Dispose method for any .NET objects that you have as components inside that class(having unmanaged resources as their member) from the Dispose method.
There're some keys about from the book MCSD Certification Toolkit (exam 70-483) pag 193:
destructor ≈(it's almost equal to) base.Finalize(), The destructor is converted into an override version of the Finalize method that executes the destructor’s code and then calls the base class’s Finalize method. Then its totally non deterministic you can't able to know when will be called because depends on GC.
If a class contains no managed resources and no unmanaged resources, it shouldn't implement IDisposable or have a destructor.
If the class has only managed resources, it should implement IDisposable but it shouldn't have a destructor. (When the destructor executes, you can’t be sure managed objects still
exist, so you can’t call their Dispose() methods anyway.)
If the class has only unmanaged resources, it needs to implement IDisposable and needs a destructor in case the program doesn’t call Dispose().
Dispose() method must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before.
Dispose() should free both managed and unmanaged resources.
The destructor should free only unmanaged resources. When the destructor executes, you
can’t be sure managed objects still exist, so you can’t call their Dispose methods anyway. This is obtained by using the canonical protected void Dispose(bool disposing) pattern, where only managed resources are freed (disposed) when disposing == true.
After freeing resources, Dispose() should call GC.SuppressFinalize, so the object can
skip the finalization queue.
An Example of a an implementation for a class with unmanaged and managed resources:
using System;
class DisposableClass : IDisposable
{
// A name to keep track of the object.
public string Name = "";
// Free managed and unmanaged resources.
public void Dispose()
{
FreeResources(true);
// We don't need the destructor because
// our resources are already freed.
GC.SuppressFinalize(this);
}
// Destructor to clean up unmanaged resources
// but not managed resources.
~DisposableClass()
{
FreeResources(false);
}
// Keep track if whether resources are already freed.
private bool ResourcesAreFreed = false;
// Free resources.
private void FreeResources(bool freeManagedResources)
{
Console.WriteLine(Name + ": FreeResources");
if (!ResourcesAreFreed)
{
// Dispose of managed resources if appropriate.
if (freeManagedResources)
{
// Dispose of managed resources here.
Console.WriteLine(Name + ": Dispose of managed resources");
}
// Dispose of unmanaged resources here.
Console.WriteLine(Name + ": Dispose of unmanaged resources");
// Remember that we have disposed of resources.
ResourcesAreFreed = true;
}
}
}
99% of the time, you should not have to worry about either. :) But, if your objects hold references to non-managed resources (window handles, file handles, for example), you need to provide a way for your managed object to release those resources. Finalize gives implicit control over releasing resources. It is called by the garbage collector. Dispose is a way to give explicit control over a release of resources and can be called directly.
There is much much more to learn about the subject of Garbage Collection, but that's a start.
The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...
Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.
The IDisposable interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.
Note that if you have a finalizer then you should also implement the IDisposable interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.
See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable.
Diff between Finalize and Dispose methods in C#.
GC calls the finalize method to reclaim the unmanaged resources(such as file operarion, windows api, network connection, database connection) but time is not fixed when GC would call it. It is called implicitly by GC it means we do not have low level control on it.
Dispose Method: We have low level control on it as we call it from the code. we can reclaim the unmanaged resources whenever we feel it is not usable.We can achieve this by implementing IDisposal pattern.
The summary is -
You write a finalizer for your class if it has reference to unmanaged
resources and you want to make sure that those unmanaged resources
are released when an instance of that class is garbage collected
automatically. Note that you can't call the Finalizer of an object explicitly - it's called automatically by the garbage collector as and when it deems necessary.
On the other hand, you implement the IDisposable interface(and
consequently define the Dispose() method as a result for your class) when your class
has reference to unmanaged resources, but you don't want to wait for
the garbage collector to kick in (which can be anytime - not in
control of the programmer) and want to release those resources as
soon as you are done. Thus, you can explicitly release unmanaged resources by calling an object's Dispose() method.
Also, another difference is - in the Dispose() implementation, you should release managed resources as well, whereas that should not be done in the Finalizer. This is because it's very likely that the managed resources referenced by the object have already been cleaned up before it's ready to be finalized.
For a class that uses unmanaged resources, the best practice is to define both - the Dispose() method and the Finalizer - to be used as a fallback in case a developer forgets to explicitly dispose off the object. Both can use a shared method to clean up managed and unmanaged resources :-
class ClassWithDisposeAndFinalize : IDisposable
{
// Used to determine if Dispose() has already been called, so that the finalizer
// knows if it needs to clean up unmanaged resources.
private bool disposed = false;
public void Dispose()
{
// Call our shared helper method.
// Specifying "true" signifies that the object user triggered the cleanup.
CleanUp(true);
// Now suppress finalization to make sure that the Finalize method
// doesn't attempt to clean up unmanaged resources.
GC.SuppressFinalize(this);
}
private void CleanUp(bool disposing)
{
// Be sure we have not already been disposed!
if (!this.disposed)
{
// If disposing equals true i.e. if disposed explicitly, dispose all
// managed resources.
if (disposing)
{
// Dispose managed resources.
}
// Clean up unmanaged resources here.
}
disposed = true;
}
// the below is called the destructor or Finalizer
~ClassWithDisposeAndFinalize()
{
// Call our shared helper method.
// Specifying "false" signifies that the GC triggered the cleanup.
CleanUp(false);
}
The best example which i know.
public abstract class DisposableType: IDisposable
{
bool disposed = false;
~DisposableType()
{
if (!disposed)
{
disposed = true;
Dispose(false);
}
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
Dispose(true);
GC.SuppressFinalize(this);
}
}
public void Close()
{
Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// managed objects
}
// unmanaged objects and resources
}
}
The main difference between Dispose and Finalize is that:
Dispose is usually called by your code. The resources are freed instantly when you call it. People forget to call the method, so using() {} statement is invented. When your program finishes the execution of the code inside the {}, it will call Dispose method automatically.
Finalize is not called by your code. It is mean to be called by the Garbage Collector (GC). That means the resource might be freed anytime in future whenever GC decides to do so. When GC does its work, it will go through many Finalize methods. If you have heavy logic in this, it will make the process slow. It may cause performance issues for your program. So be careful about what you put in there.
I personally would write most of the destruction logic in Dispose. Hopefully, this clears up the confusion.
Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.
In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.
Note that even when you provide explicit control by way of 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.
I searched the answer to this question a lot today. I will share my learnings here. My answer is based on this link, because it has the clearest explanation I have seen.
When your objects has access to unmanaged resources, you have to manually release those resources. This can be done via IDisposable or finalizer meaning they both release unmanaged resources.
Rule of thumb:
Implement IDisposable to release unmanaged resources and caller code must call Dispose method. If caller forgets to call Dispose() method, you still can provide a method to release those unmanaged resources. First option is using safe handle to wrap unmanaged resource. Second option is defining a finalizer. Using safe handle is recommended way in this case.
I think this link is the clearest answer to this question. I do not know why people provide complex explanations to this question on the internet. It made me feel confused until I find that link.
As we know dispose and finalize both are used to free unmanaged resources..
but the difference is finalize uses two cycle to free the resources , where as dispose uses one cycle..
To answer on the first part you should provide examples where people use
different approach for the exact same class-object.
Otherwise it is difficult (or even strange) to answer.
As for the second question better read first this
Proper use of the IDisposable interface
which claims that
It's your choice! But choose Dispose.
In other words: The GC only knows about finalizer (if any. Also known as destructor to Microsoft).
A good code will attempt to cleanup from both (finalizer and Dispose).

Categories

Resources