代码之家  ›  专栏  ›  技术社区  ›  rjzii

CA2202针对OracleConnection处理的代码分析警告

  •  0
  • rjzii  · 技术社区  · 14 年前

    我们从VisualStudio2010中的代码分析中得到以下警告,我想知道这是一个误报,我们可以安全地忽略它,还是应该重构代码以正确地处理对象。

    相关代码:

    public void MyFunction()
    {
        OracleConnection 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();
            }
        }
    }
    

    相关错误消息:

    警告18 CA2202:Microsoft。用法:可以释放对象“oraConnection” 在方法“ClassName.MyFunction()”中多次使用。避免产生 System.ObjectDisposedException不应调用多个Dispose 物体上的时间。

    1 回复  |  直到 14 年前
        1
  •  1
  •   to StackOverflow    14 年前

    如果删除该行:

    oraConnection.Close();
    

    您可能还希望用using语句替换try/finally。

    请注意,Microsoft自己的指导方针规定,IDisposable.Dispose的实现方式应确保可以安全地多次调用它。这意味着可以安全地忽略CA2202警告,如中所述 the comment by JoeM27 on the MSDN page for CA2202