Chapter62:IDisposableinterface

No Comments

Section62.1:Inaclassthatcontainsonlymanagedresources

Managedresourcesareresourcesthattheruntime’sgarbagecollectorisawareandundercontrolof.Thereare manyclassesavailableintheBCL,forexample,suchasaSqlConnectionthatisawrapperclassforanunmanaged resource.TheseclassesalreadyimplementtheIDisposableinterface–it’suptoyourcodetocleanthemupwhen you are done.

It’snotnecessarytoimplementafinalizerifyourclassonlycontainsmanagedresources.

publicclassObjectWithManagedResourcesOnly:IDisposable

{

privateSqlConnectionsqlConnection=newSqlConnection();

publicvoidDispose()

{

sqlConnection.Dispose();

}

}

Section62.2:Inaclasswithmanagedandunmanaged resources

It’simportanttoletfinalizationignoremanagedresources.Thefinalizerrunsonanotherthread–it’spossiblethat themanagedobjectsdon’texistanymorebythetimethefinalizerruns.ImplementingaprotectedDispose(bool)methodisacommonpracticetoensuremanagedresourcesdonothavetheirDisposemethodcalledfroma finalizer.

publicclassManagedAndUnmanagedObject:IDisposable

{

privateSqlConnectionsqlConnection=newSqlConnection();

privateUnmanagedHandleunmanagedHandle=Win32.SomeUnmanagedResource();

privatebooldisposed;

publicvoidDispose()

{

Dispose(true);//clientcalleddispose

GC.SuppressFinalize(this);//telltheGCtonotexecutetheFinalizer

}

protectedvirtualvoidDispose(booldisposeManaged)

{

if(!disposed)

{

if(disposeManaged)

{

if(sqlConnection!=null)

{

sqlConnection.Dispose();

}

}

unmanagedHandle.Release();

disposed=true;

}

}

~ManagedAndUnmanagedObject()

{

Dispose(false);

}

}

Section62.3:IDisposable,Dispose

.NETFrameworkdefinesainterfacefortypesrequiringatear-downmethod:

publicinterfaceIDisposable

{

voidDispose();

}

Dispose()isprimarilyusedforcleaningupresources,likeunmanagedreferences.However,itcanalsobeusefulto forcethedisposingofotherresourceseventhoughtheyaremanaged.InsteadofwaitingfortheGCtoeventually alsocleanupyourdatabaseconnection,youcanmakesureit’sdoneinyourownDispose()implementation.

publicvoidDispose()

{

if(null!=this.CurrentDatabaseConnection)

{

this.CurrentDatabaseConnection.Dispose();

this.CurrentDatabaseConnection=null;

}

}

Whenyouneedtodirectlyaccessunmanagedresourcessuchasunmanagedpointersorwin32resources,createa class inheriting from SafeHandleand use that class’sconventions/tools to do so.

Section62.4:usingkeyword

WhenanobjectimplementstheIDisposableinterface,itcanbecreatedwithintheusingsyntax:

using(varfoo=newFoo())

{

//dofoostuff

}//whenitreachesherefoo.Dispose()willgetcalled

publicclassFoo:IDisposable

{

publicvoidDispose()

{

Console.WriteLine(“disposecalled”);

}

}

Viewdemo

usingissyntaticsugarforatry/finallyblock;theaboveusagewouldroughlytranslateinto:

{

varfoo=newFoo();

try

{

//dofoostuff

}

finally

{

if (foo!=null) ((IDisposable)foo).Dispose();

}

}

Section62.5:Inaninheritedclasswithmanagedresources

It’sfairlycommonthatyoumaycreateaclassthatimplementsIDisposable,andthenderiveclassesthatalso containmanagedresources.ItisrecommendededtomarktheDisposemethodwiththevirtualkeywordsothat clientshavetheabilitytocleanupanyresourcestheymayown.

publicclassParent:IDisposable

{

privateManagedResourceparentManagedResource=newManagedResource();

publicvirtualvoidDispose()

{

if(parentManagedResource!=null)

{

parentManagedResource.Dispose();

}

}

}

publicclassChild:Parent

{

privateManagedResourcechildManagedResource=newManagedResource();

publicoverridevoidDispose()

{

if(childManagedResource!=null)

{

childManagedResource.Dispose();

}

//cleanuptheparent’sresources

base.Dispose();

}

}

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts