简体   繁体   English

Visual Studio代码分析警告-多次处置[CA2202]

[英]Visual Studio Code Analysis Warning - Multiple Dispose [CA2202]

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

I get this error using dispose : 我使用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);
            }

SqlConnection.Close() is the functionally the same as SqlConnection.Dispose() . SqlConnection.Close()在功能上与SqlConnection.Dispose()相同。

Therefore these lines of code will dispose the connection twice if the state is not already closed: 因此,如果状态尚未关闭,则这些代码行将对连接进行两次处置:

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

You only need the Dispose() . 您只需要Dispose()

To clarify, the implementation of SqlConnection.Dispose() is: 澄清一下, 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);
}

It seems that CodeAnalysis knows about this, and is issuing the warning. 似乎CodeAnalysis对此有所了解,并发出了警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM