How should I correctly dispose of an object?

你离开我真会死。 提交于 2019-12-11 02:37:28

问题


I frequently use the following code (or alike) to dispose of objects:

SqlCommand vCmd = null;

try 
{
    // CODE
}
catch(Exception ex) { /* EXCEPTION HANDLE */ }
finally 
{
    if (vCmd != null) 
    {
        vCmd.Dispose();
        vCmd = null;
    }
}

Is this the best way to release objects and dispose of objects?

I'm using the VS analytics and give me a warning about redundancies. But I always do it this way...


回答1:


Here is an example from MSDN:

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

Note the use of "using" for the connection.

Back in the Olden Days of COM/ActiveX, you needed to set your objects to "Nothing".

In managed code, this is no longer necessary.

You should neither call "Dispose()", nor set your sqlCommand to "null".

Just stop using it - and trust the .Net garbage collector to do the rest.




回答2:


The best way in terms of readability is using the using statement:

using(SqlCommand vCmd = new SqlCommand("...", connection)
{
    try 
    {
        // CODE
    }
    catch(Exception ex) 
    { 
        // EXCEPTION HANDLE
    }
}

It disposes objects even in case of error, so similar to a finally. You should use it always when an object implements IDisposable which indicates that it uses unmanaged resources.

Further reading:

  • Cleaning Up Unmanaged Resources
  • there is no need to set objects to null.


来源:https://stackoverflow.com/questions/24440824/how-should-i-correctly-dispose-of-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!