As we all know, garbage collection can be divided into two categories of Dispose and finalize, there are too many differences between them, one is the normal garbage collection GC called the method, the other is the Terminator finalizer, the method called, in effective C # book, There is a clear suggestion that the IDispose interface should be used instead of finalize. The reason is because finalize finalization increases the algebra of garbage collection objects, which affects garbage collection.
For the above reasons, we now only look at classes that use the IDispose interface.
In. NET, the vast majority of classes are run in a managed environment, so the GC is responsible for recycling, so we do not need to implement the IDispose interface, but the GC is responsible for the move. But some classes use unmanaged resources, so this time, we should go to implement IDispose interface, say a more commonly used SqlConnection and so on.
Write a section of the commonly used connection SQL statement model:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings ["Study1ConnectionString1"].ConnectionString;
SqlConnection thisConnection = new SqlConnection(connectionString);
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * from [User]";
thisCommand.ExecuteNonQuery();
thisConnection.Close();
In fact, as unmanaged resources, in order to prevent us from forgetting to call close, we generally implement finalize, so even if we do not close off, the finalizer will reclaim this memory. However, the algebra of this piece of rubbish is added.
Let's say we wrote this code:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings ["Study1ConnectionString1"].ConnectionString;
SqlConnection thisConnection = new SqlConnection(connectionString);
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * form [User]"; //SQL语句错误
thisCommand.ExecuteNonQuery();
thisConnection.Close();
In this case, we open the SqlConnection is not closed, can only wait for finalize to shut down.
This is a very bad practice. So we can think of exception handling:
SqlConnection thisConnection = null;
try
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings ["Study1ConnectionString1"].ConnectionString;
thisConnection = new SqlConnection(connectionString);
thisConnection.Open();
SqlCommand thisCommand = new SqlCommand();
thisCommand.Connection = thisConnection;
thisCommand.CommandText = "select * form [User]";
thisCommand.ExecuteNonQuery();
}
finally
{
if (thisConnection != null)
{
thisConnection.Close();
}
}