![](/img/trans.png)
[英]The dreaded CA2202 warning in Visual Studio Code Analysis
[英]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
我使用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()
在功能上與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對此有所了解,並發出了警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.