Information Technology Reference
In-Depth Information
nonmemory resources are freed later, when finalizers get their chance to
execute. All those objects then stay in memory that much longer, and your
application becomes a slowly executing resource hog.
Luckily for you, the C# language designers knew that explicitly releasing
resources would be a common task. They added keywords to the language
that make it easy.
Suppose you wrote this code:
public void ExecuteCommand( string connString,
string commandString)
{
SqlConnection myConnection = new SqlConnection (
connString);
SqlCommand mySqlCommand = new SqlCommand (commandString,
myConnection);
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
Tw o d i s p o s a b l e o b j e c t s a r e n o t p r o p e r l y c l e a n e d u p i n t h i s e x a m p l e :
SqlConnection and SqlCommand. Both of these objects remain in mem-
ory until their finalizers are called. (Both of these classes inherit their final-
izer from System.ComponentModel.Component.)
Yo u fi x t h i s p r o b l e m b y c a l l i n g D i s p o s e w h e n y o u a r e fi n i s h e d w i t h t h e
command and the connection:
public void ExecuteCommand( string connString,
string commandString)
{
SqlConnection myConnection = new SqlConnection (
connString);
SqlCommand mySqlCommand = new SqlCommand (commandString,
myConnection);
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
mySqlCommand.Dispose();
myConnection.Dispose();
}
Search WWH ::




Custom Search