开发者

CA2202 Warning from Code Analysis for OracleConnection disposal

开发者 https://www.devze.com 2023-01-04 03:38 出处:网络
We are getting the following warning from Code Analysis in Visual Studio 2010 and I\'m wondering if this is a false positive that we can safely ignore or the code should be refactored to correctly dis

We are getting the following warning from Code Analysis in Visual Studio 2010 and I'm wondering if this is a false positive that we can safely ignore or the code should be refactored to correctly dispose the object.

The relevant code:

public void MyFunction()
{
    Oracle开发者_如何学CConnection oraConnection = null;
    OracleCommand oraCommand = null;

    try
    {
        // Connect to the database
        oraConnection = new OracleConnection(connectionString);
        oraConnection.Open();
        // Prepare and run the query
        oraCommand = new OracleCommand(sqlQuery, oraConnection);
        oraCommand.ExecuteNonQuery();
    }
    catch { throw; }
    finally
    {
        // Perform a safe cleanup
        if (oraCommand != null) { oraCommand.Dispose(); }
        if (oraConnection != null)
        {
            oraConnection.Close();
            oraConnection.Dispose();
        }
    }
}

The relevant error message:

Warning 18 CA2202 : Microsoft.Usage : Object 'oraConnection' can be disposed more than once in method 'ClassName.MyFunction()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.


If you remove the line:

oraConnection.Close();

it should get rid of the warning, since closing and disposing a connection are essentially the same thing.

You might also want to replace your try/finally by a using statement.

Note that Microsoft's own guidelines say that IDisposable.Dispose should be implemented in such a way that it can safely be called multiple times. Which means that the CA2202 warning can safely be ignored, as noted in the comment by JoeM27 on the MSDN page for CA2202.

0

精彩评论

暂无评论...
验证码 换一张
取 消