On the Usage and Benefits of C using

  • 2021-09-20 21:20:05
  • OfStack

There is a usage of using in the code in the previous article, and I just started to look at some information and said it was a command to force the object to be closed. Today, after checking some data, I realized that the original using instruction called a method-Dispose () method. The function of Dispose () method is to release all the used resources.

Example:


public void ExecuteCommand( string connString, string commandString ) 
{ 
 SqlConnection myConnection = new SqlConnection( connString ); 
 SqlCommand mySqlCommand = new SqlCommand( commandString, 
  myConnection ); 
 
 myConnection.Open(); 
 mySqlCommand.ExecuteNonQuery(); 
} 

Two handleable objects in this example were not properly released: SqlConnection and SqlCommand. Both objects are stored in memory at the same time until the destructor is called.

The way to solve this problem is to call the Dispose of commands and links after using them:


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( ); 
} 

This function can also be realized well by using using statement, and the code is very clear:


public void ExecuteCommand( string connString, string commandString ) 
{ 
 using ( SqlConnection myConnection = new  SqlConnection( connString )) 
 { 
  using ( SqlCommand mySqlCommand = new SqlCommand( commandString, myConnection )) 
  { 
   myConnection.Open(); 
   mySqlCommand.ExecuteNonQuery(); 
  } 
 } 
} 

When you use a handleable object within a function, the using statement is the easiest way to ensure that the object is properly disposed of. When these objects are allocated, they are put into an try/finally block by the compiler.


SqlConnection myConnection = null; 
 
// Example Using clause: 
using ( myConnection = new SqlConnection( connString )) 
{ 
 myConnection.Open(); 
} 
 
 
// example Try / Catch block: 
try { 
 myConnection = new SqlConnection( connString ); 
 myConnection.Open(); 
} 
finally { 
 myConnection.Dispose( ); 
} 

Sometimes when using the try/finally block, you will find that if an error occurs, the program will not report an error. I feel that it is better to use using statement.
The above is the whole content of this paper, hoping to help everyone's study.


Related articles: