Visual Studio代码分析警告 - 多个处理[CA2202]

时间:2015-03-20 13:25:40

标签: c#

CA2202  Do not dispose objects multiple times   Object 'con' can be disposed more than once in method 'CreateHandheldDataViewModel.CreateSDF2(int, string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: Lines: 647  DFStore.Modules.Store   CreateHandheldDataViewModel.cs  647

我使用dispose收到此错误:

 private void CreateSDF2(int depoId, string fileName)
            {
                string cnnStr = String.Format("Data Source = {0}", fileName);

                var sqlEngine = new SqlCeEngine(cnnStr);
                sqlEngine.CreateDatabase();
                sqlEngine.Dispose();

                var con = new SqlCeConnection(cnnStr);
                var command = new SqlCeCommand { Connection = con };
                String[] createDbScripts = GetCreateDBScript2().Split(new[] { " go " }, StringSplitOptions.RemoveEmptyEntries);

                if (con.State != ConnectionState.Open)
                    con.Open();
                foreach (String s in createDbScripts)
                {
                    command.CommandText = s;
                    command.ExecuteNonQuery();
                }
                if (con.State != ConnectionState.Closed)
                    con.Close();

                con.Dispose();

                InsertDatatoDB2(depoId, fileName);
            }

1 个答案:

答案 0 :(得分:2)

SqlConnection.Close()在功能上与SqlConnection.Dispose()相同。

因此,如果状态尚未关闭,这些代码行将处理两次连接:

if (con.State != ConnectionState.Closed)
    con.Close();
con.Dispose();

您只需要Dispose()

澄清一下,SqlConnection.Dispose()的实施是:

public void Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close(); // <---------- It calls Close()
    }                 
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

CodeAnalysis似乎知道这一点,并发出警告。