Friday, 23 May 2014

What is the use/significance of Dispose and Finalize method?

.NET Framework provides two methods Finalize and Dispose for releasing unmanaged resources like: Windows API created objects, File, Database connection objects, COM objects.
It is always recommended to use Dispose method to clean unmanaged resources. Do not implement the Finalize method until it is extremely necessary
Dispose:

Dispose method belongs to ‘IDisposable’ interface. If any object wants to release its unmanaged code, the best is to implement IDisposable and override the Dispose method  of IDisposable interface. Now once your class has exposed the Dispose method, it is the responsibility of the client to call the Dispose method to do the cleanup. 


How do I force the Dispose method to be called automatically, as clients can forget to call Dispose method?

Call the Dispose method in Finalize method and in Dispose method, suppress the finalize method using GC.SuppressFinalize.

Below is the sample code of the pattern. This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice.

 public class CleanClass : IDisposable
    {
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
        
        ~CleanClass()
        {
            Dispose();
         }
    }

Finalize:

.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (example: Windows API created objects, File, Database connection objects, COM objects, etc.) are outside the scope of .NET Framework. We have to explicitly clean our resources. For these types of objects, .NET Framework provides
Object.Finalize method.


What is the difference between Finalize() and Dispose() methods?

Dispose:
  1. Dispose It belongs to IDisposable interface. and internal called by user code.
  2. Dispose () of IDisposable interface is called by the programmer to explicitly release resources when they are no longer being used. Dispose () can be called even if other references to the object are alive.
  3. It is called by user code and the class implementing dispose method must implement IDisposable interface.It belongs to IDisposable interface.Implement this when you are writing a custom class that will be used by other users.There is no performance costs associated with Dispose method
Finalize:
  1. Finalize It belongs to Object class. and It's implemented with the help of destructor in C#.
  2. Used to free unmanaged resources like files, database connections, COM etc. held by an object before that object is destroyed.Internally, it is called by Garbage Collector and cannot be called by user code.
  3. 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).

Why is it preferred to not use finalize for clean up?

The problem with f
inalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods.

Let us assume, there are three objects, Object1Object2, and Object3

Object2 has the finalize method overridden and remaining objects do not have the finalize method overridden.

Now when garbage collector runs for the first time, it searches for objects whose memory has to free. It can see three objects but only cleans the memory for Object1 and Object3

Object2 it pushes to the finalization queue.

Now garbage collector runs for the second time. It sees there are no objects to be released and then checks for the finalization queue and at this moment, it clears object2 from the memory. 

So if you notice, 
object2 was released from memory in the second round and not first. That is why the best practice is not to write clean up non.NET/unmanaged resources in Finalize method rather use the DISPOSE.

What is the purpose of the Using block in C#?

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

public class Debuggersspace : IDisposable
{
 //implementation details...
}



These are equivalent:
Debuggersspace qa = new Debuggersspace ();
try 
{
        qa.Action();
}
finally
{
       if (qa != null)
       qa.Dispose();
}

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed

using (Debuggersspace qa = new Debuggersspace ())
{
    qa.Action(); 
}
Points to remember:
  1. If you declare the variable outside the using block and then create a new instance in the using statement it may not dispose the item
  2. So the using statement will automatically dispose of the object once that context is complete.
  3. The using statement is used to work with an object in C# that implements the IDisposableinterface.
  4. The IDisposable interface has one public method called Dispose that is used to dispose of the object.
  5. we use the using statement, we don't need to explicitly dispose of the object in the code, the using statement takes care of it.


C# Disposable pattern, Using, Dispose Vs Finalize:




Please refer below links for more information:


No comments:

Post a Comment

How to improve applications performance which is hosted in cloud ?

Improving the performance of an application hosted in Microsoft Azure involves a combination of optimizing your application code, leveraging...