1.implictly resource
cleanup (Destructors) : under the control of Garbage collector
2.Explict resource
cleanup(IDispose-Dispose() method) : under the control of Developer
Implict Resource Clenup
What is the role of
Garbage Collector in Disposing objects?
Yes, Garbage collector
also dispose the objects implictly with the help of finallse() method of object(GC)
but only managed objects and with the help of unreachable/unused objects
mechanism of garbage collector. Implict Resource Cleanup.
We can define destrutor
for any type by defining the Destructors.then Garbage Collector implictly
generates try and finally blocks (like using block) and calls the Finialize()
method of object.
class FinializeDemo
{
~FinializeDemo()
{
// generates try and finally block
by CLR.
}
static void Main()
{
Console.Write("welcomdssss");
}
}
Above destructor(~FinializeDemo())
automatically calls the Finialize method of object automatically..
Object destruction is
under the control of Garbage Collector(not control by developers).
Garbage Collector is a
static class which has Collect method to Developer to Forcebly destory the
objects from Various Generations of GC mechanisum.
Like
~FinializeDemo()
{
GC.collect()
; // various
generations// Gen1/2/3 and conditions
}
How to use Expliect
Resource Cleanup for objects Memory allocation?
Yes, to perform Explict
Resource Cleanup is done with the types which impliments IDispose interface.
Ex :
Explict Resource
Cleanup is done with Disposing objects expliectly. By calling Dispose method of
IDispose Interface.
Static void Main()
{
sqlConnection con=new Sqlconnection();
con.Dispose();
}
Which call the Dispose
method of sqlconnection for freeup the resource. Instead of calling Destructor
of sqlconnection.
Dbconnection implements
the IDispose method.
Inside Dispose
public void
Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // it won't call the destractor of sqlconnection class
}
protected override void
Dispose(bool Diposing)
{
if
(!IsDisposed)
{
if
(Diposing)
{
con.Dispose();
//Clean Up managed resources
}
else
{
//
not disposed till now impliectly
}
/Clean up
unmanaged resources
}
IsDisposed = true;
}
How to use impliectly Resource Cleanup for objects Memory allocation?
Which is done by
calling Finialize method of destructor. If we not write desturctor for our
type. Base class Object of Finialize() is called implictly.
Class SampleDemo
{
static void Main()
{
FinializeDemo fobj = new FinializeDemo();
}
}
Class FinializeDemo()
{
~FinializeDemo()
{
Dispose(false);
}
protected override void
Dispose(bool Diposing)
{
if
(!IsDisposed)
{
if
(Diposing)
{
con.Dispose();
//Clean Up managed resources
}
else
{
//
not disposed till now impliectly
}
}
IsDisposed = true;
}
}
No comments:
Post a Comment