我有一个工厂方法来构建实现的对象IDisposable.最终,调用者可以管理创建对象的生命周期.这种设计引发了一堆CA2000错误.在我的设计中是否存在根本不正确的东西,是否需要重构,还是仅仅对静态代码分析警告过于兴奋?
工厂方法
public static DisposableType BuildTheDisposableType(string param1, int param2)
{
var theDisposable = new DisposableType();
// Do some work to setup theDisposable
return theDisposable
}
Run Code Online (Sandbox Code Playgroud)
来电者
using(var dt = FactoryClass.BuildTheDisposableType("data", 4))
{
// use dt
}
Run Code Online (Sandbox Code Playgroud) 我使用的DataVisualization.Charting.Chart很多,而且大部分都在使用.但是,我经常运行代码分析,并自己处理警告.但是,使用图表的*.Designer.cs文件中大约有30个CA2000(未沿所有异常路径布置的对象).Designer文件几乎生成了所有图表代码,几乎所有图表元素都实现了IDisposable.我在项目首选项中选中了"从生成的代码中抑制结果",但它仍然可以.
有没有办法解决这个问题,而不必手动创建图表对象,并且不会禁用该类中其余代码的代码分析?有没有办法为所有.Designer.cs文件禁用它?或者,是否有解决方案通过使设计师代码处理来正确删除这些警告?
当我通过Visual Studio的代码分析实用程序运行一些代码时,我收到一个警告,我不确定如何解决.也许这里的某个人遇到了类似的问题,解决了这个问题,并愿意分享他们的见解.
我正在编写DataGridView控件中使用的自定义绘制单元格.代码类似于:
public class DataGridViewMyCustomColumn : DataGridViewColumn
{
public DataGridViewMyCustomColumn() : base(new DataGridViewMyCustomCell())
{
}
Run Code Online (Sandbox Code Playgroud)
它会生成以下警告:
CA2000:Microsoft.Reliability:在方法'DataGridViewMyCustomColumn.DataGridViewMyCustomColumn()'中,在对所有引用超出范围之前,对对象'new DataGridViewMyCustomCell()'调用System.IDisposable.Dispose.
我知道它警告我DataGridViewMyCustomCell(或它继承自的类)实现了IDisposable接口,并且应该调用Dispose()方法来清理DataGridViewMyCustomCell声明的任何资源.
我在互联网上看到的示例建议使用块来限制对象的生命周期并让系统自动处理它,但是当移动到构造函数的主体中时无法识别base,因此我无法编写使用阻止它...我不确定我还想要做什么,因为不会指示运行时释放仍然可以在以后在基类中使用的对象?
我的问题是,代码是否正常?或者,如何重构以解决警告?除非确实合适,否则我不想压制警告.
我有很多像这样的代码:
FileStream fs = File.Open(@"C:\Temp\SNB-RSS.xml", FileMode.Open);
using (XmlTextReader reader = new XmlTextReader(fs))
{
/* Some other code */
}
Run Code Online (Sandbox Code Playgroud)
这给了我以下代码分析警告:
CA2000 : Microsoft.Reliability : In method 'SF_Tester.Run()', object 'fs' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'fs' before all references to it are out of scope.
Run Code Online (Sandbox Code Playgroud)
如果我按照建议操作并将File.Open放在using语句中,我会得到:
CA2202 : Microsoft.Usage : Object 'fs' can be disposed more than once in method 'SF_Tester.Run()'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time …Run Code Online (Sandbox Code Playgroud) 虽然之前已经讨论了主题,但建议的解决方案似乎不起作用..
我在表单应用程序中有一个按钮单击回调方法,它显示了一个文件夹选择器对话框:
private void ButtonSelectReporterFolderClick(object sender, EventArgs e)
{
using (var dialog = new FolderBrowserDialog()) // causes warning
{
if (dialog.ShowDialog() == DialogResult.OK)
{
this.boxReporterFolderPath.Text = dialog.SelectedPath;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生一个警告:
CA2000: Microsoft.Reliability : In method 'MainWindow.ButtonSelectReporterFolderClick(object, EventArgs)', object '<>g__initLocal' is not disposed along all exception paths. Call System.IDisposable.Dispose on object '<>g__initLocal' before all references to it are out of scope.
我也试过使用try- finally块甚至调用dialog.Dispose没有任何块,一切都无济于事 - 警告仍然存在,始终在初始化线.
CA2000是关于IDisposable接口的警告:
CA2000:Microsoft.Reliability:在方法'ImportProcessor.GetContext(string)'中,在对所有引用超出范围之前,在对象'c'上调用System.IDisposable.Dispose.
我的方法用于存储上下文缓存,如下所示:
public class RegionContext : IDisposable { /* Implement Dispose() here */ }
private Dictionary<string, RegionContext> contextCache = new ..... ();
public RegionContext GetContext(string regionCode)
{
RegionContext rc = null;
if (!this.contextCache.TryGetValue(regionCode.ToUpper(), out rc))
{
rc = new RegionContext(regionCode);
this.contextCache.Add(regionCode.ToUpper(), rc);
}
return rc;
}
Run Code Online (Sandbox Code Playgroud)
你会在哪里使用using()修复此编译器警告的语句?
我的外部类实际上会迭代并处理contextCache其自己的实现中的内容.我要压制它,还是有办法正确摆脱这个警告?
我正在使用.net并且需要获取一些html文本,所以我想我会一起使用HtmlTextWriter和StringWriter来获得格式正确的html.但是,尽管编写代码的方式各不相同,我仍然会收到静态代码分析器的警告(使用Microsoft All Rules).在下面的代码示例中,我在注释中显示代码分析器警告.为了简化代码,我实际上并没有对HtmlTextWriter进行任何调用(您将在每个函数中看到对该效果的注释).如何正确编写代码以避免警告?
// CA2000 : Microsoft.Reliability : In method 'Default.Func1()', object 'stringWriter' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'stringWriter' before all references to it are out of scope.
public static string Func1()
{
string html;
StringWriter stringWriter;
using (var writer = new HtmlTextWriter(stringWriter = new StringWriter()))
{
// You would do some stuff with the writer here, but not for this example.
html = stringWriter.ToString();
}
return html;
}
// CA2202 : Microsoft.Usage : …Run Code Online (Sandbox Code Playgroud) 我有一个功能,我认为我已经修复了代码分析中的CA2000警告,但它不会消失.警告在SqlCommand上.这是功能:
protected internal void LogUserSession(int? managerID)
{
using (var sqlCommand = new SqlCommand())
{
sqlCommand.SetCommand("usp_UserActivity_Create");
SqlParameter prmSessionID = new SqlParameter();
prmSessionID.ParameterName = "@sessionID";
prmSessionID.Direction = ParameterDirection.Input;
prmSessionID.SqlDbType = SqlDbType.VarChar;
prmSessionID.Size = 32;
prmSessionID.SetValue(SessionID);
SqlParameter prmUsername = new SqlParameter();
prmUsername.ParameterName = "@username";
prmUsername.Direction = ParameterDirection.Input;
prmUsername.SqlDbType = SqlDbType.VarChar;
prmUsername.Size = 32;
prmUsername.SetValue(Username);
SqlParameter prmLoginID = new SqlParameter();
prmLoginID.ParameterName = "@loginID";
prmLoginID.Direction = ParameterDirection.Output;
prmLoginID.SqlDbType = SqlDbType.Int;
sqlCommand.Parameters.Add(prmSessionID);
sqlCommand.Parameters.Add(prmUsername);
sqlCommand.Parameters.Add(prmLoginID);
using (sqlCommand.Connection = new SqlConnection(ConnectionStrings.MainApp))
{
sqlCommand.Connection.Open();
sqlCommand.ExecuteNonQueryTryCatch();
if (prmLoginID.Value != DBNull.Value) …Run Code Online (Sandbox Code Playgroud) 我收到第84行和第85行的消息(两个,使用行堆叠):
CA2000:Microsoft.Reliability:在方法'RavenDataAccess.GetRavenDatabase()'中,对象'<> g_ initLocal9'未沿所有异常路径放置.在对对象'<> g _initLocal9'的所有引用都超出范围之前,调用System.IDisposable.Dispose.
DocumentStore实现了IDisposable.
为什么?我还能如何处置DocumentStore对象?它们是在一个使用块中创建的,我将它们放在我的catch块中.该如何修复?
private static IDocumentStore GetRavenDatabase()
{
Shards shards = new Shards();
try
{
using (DocumentStore docStore1 = new DocumentStore { Url = ConfigurationManager.AppSettings["RavenShard1"] }) // Line 84
using (DocumentStore docStore2 = new DocumentStore { Url = ConfigurationManager.AppSettings["RavenShard2"] }) // Line 85
{
shards.Add(docStore1);
shards.Add(docStore2);
}
using (ShardedDocumentStore documentStore = new ShardedDocumentStore(new ShardStrategy(), shards))
{
documentStore.Initialize();
IndexCreation.CreateIndexes(typeof(RavenDataAccess).Assembly, documentStore);
return documentStore;
}
}
catch
{
shards.ForEach(docStore => docStore.Dispose());
throw;
}
}
Run Code Online (Sandbox Code Playgroud) 这是我的代码,它给了我CA2000"new DataTable()..."和"new DataColumn()..."
usersDS.Tables.Add(new DataTable()
{
TableName = "Users",
Columns = { new DataColumn() { ColumnName = "Handle", DataType = typeof(string) }, new DataColumn() { ColumnName = "Nickname" ,DataType = typeof(string) } }
});
Run Code Online (Sandbox Code Playgroud)
是否可以在不声明变量的情况下进行修复?
我目前正在使用websockets开发一些桌面应用程序(更准确地说:我正在使用Alchemy WebSockets).到现在为止,我的代码工作正常,但Visual Studio 2010告诉我
Warning 2 CA2000 : Microsoft.Reliability : In method 'ServerController.SetupServer(int)', call System.IDisposable.Dispose on object '<>g__initLocal0' before all references to it are out of scope. C:\Users\MaRiedl\documents\visual studio 2010\Projects\Alchemy-WebSockets\AWS-Server\ServerController.cs 38 AWS-Server
Run Code Online (Sandbox Code Playgroud)
我已经尝试用MSDN帮助(http://msdn.microsoft.com/en-us/library/ms182289.aspx)和(当然)通过日夜搜索stackoverflow.com 来解决这个问题(使用"使用"在C#) - 但遗憾的是它不会变得更好.
所以这是我的问题:我是否能够"找到"找不到的问题,或者这只是Visual Studio 2010中的误报?
这是我正在努力解决的一段代码:
private WebSocketServer _webSocketServer;
private void SetupServer(int port)
{
// set port and configure authorized ip addresses to connect to the server
_webSocketServer = new WebSocketServer(port, IPAddress.Any)
{
OnReceive = OnReceive,
OnSend = OnSend,
OnConnect = OnConnect, …Run Code Online (Sandbox Code Playgroud) ca2000 ×11
c# ×10
idisposable ×4
dispose ×3
ca2202 ×2
.net ×1
analysis ×1
constructor ×1
fxcop ×1
mschart ×1
optimization ×1
ravendb ×1
reliability ×1
stringwriter ×1
using ×1
websocket ×1