c# - Do I need to explicitly dispose SqlDataAdapter? -


in this thread, there's suggestion after operation, instance of sqldataadapter disposed of explicitly so.

string connstring = @"your connection string here"; string query = "select * table";  sqlconnection conn = new sqlconnection(connstring);         sqlcommand cmd = new sqlcommand(query, conn); conn.open(); sqldataadapter da = new sqldataadapter(cmd); da.fill(datatable); conn.close(); da.dispose(); 

is necessary? gc?

it highly recommended dispose idisposable objects manually. there nice syntax shortcut this:

using (sqlconnection con = new sqlconnection(connstring)) using (sqlcommand com = new sqlcommand()) using (sqldataadapter da = new sqldataadapter()) {    com.connection = con;    //etc.. } 

this way compiler make sure dispose gets called on objects created within "using" after code in curly brackets finishes executing (it uses try..finally this).

gc not responsible calling dispose on objects, it's main responsibility collect objects heap no longer referenced. 1 exception if class finalizable. in case gc make sure object's finalizer gets called first, , gets collected. can call dispose in finalizer , there nice pattern called "dispose method": http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

but general rule (with couple of exceptions): if you're instantiating object implements idisposable, it's responsibility call dispose on it.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -