The code in the previous article had a using usage, and just started looking at some data that said it was a command to force the object to close. Today, we looked up some information to understand that the using directive called a Method--dispose () method . The purpose of the Dispose () method is to release all usage resources.
Cases:
public void ExecuteCommand (string connstring, String commandstring)
{
SqlConnection myconnection = new Sqlconne Ction (connstring);
SqlCommand Mysqlcommand = new SqlCommand (CommandString,
myconnection);
Myconnection.open ();
Mysqlcommand.executenonquery ();
Two of the processing objects in this example are not properly released: SqlConnection and SqlCommand. Two objects are stored in memory at the same time until the destructor is invoked.
The solution to this problem is to call their dispose after using the commands and links:
public void ExecuteCommand (string connstring, String commandstring)
{
SqlConnection myconnection = new Sqlconne Ction (connstring);
SqlCommand Mysqlcommand = new SqlCommand (CommandString,
myconnection);
Myconnection.open ();
Mysqlcommand.executenonquery ();
Mysqlcommand.dispose ();
Myconnection.dispose ();
Using a Use statement can also be a good implementation, and the code is 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 reusable object within a function, the using statement is the simplest way to ensure that the object is properly disposed of. When these objects are assigned, they are placed in a 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 a try/finally block, you will find that if an error occurs, the program will not complain. I think it's better to use a using statement.
The above is the entire content of this article, I hope to help you learn.