繁体   English   中英

“ CA2000丢失范围之前处置对象”原因不明

[英]“CA2000 Dispose objects before losing scope ” for unknown reason

我已经签出了MSDN文档,并在此代码片段中采用了推荐的模式:

  BitmapSymbols temp = null;
  try {
    using (var source = bitmaps.Symbols) {
      temp = new BitmapSymbols(source, sizeSymbols);
    }
    _bitmapSymbols = temp;
    temp           = null;
  } finally { 
    if (temp!=null) temp.Dispose(); 
  }

有谁知道为什么在这种情况下正在报告temp 我看不到没有放置temp且未将其设置为“ null”的任何执行路径。 在此先感谢您的协助。

如果我移动分配从和对temp的使用中,从FxCop的产生同样的警告。

BitmapSymbols类实现IDisposable ,并且是多个Bitmap集合的包装器,以确保它们都在同一时间被处置。

更新:
问题如下:

无论如何,我看不出您为什么要提出此代码,而不是简单地使用:
_bitmapSymbols = new BitmapSymbols(source, sizeSymbols);

原因是如果发生异常,不遵循该模式可能会导致内存泄漏。 我正在编写一个游戏,用户可能需要运行数小时或数天而无需重新启动,因此避免内存泄漏对于稳定性至关重要。

甚至当图案MSDN文档中推荐的原因(两个独立的情况下)为误报我终于跌跌撞撞这里 失去范围遵循之前CA2000释放对象

  1. 如果临时可弃变量的名称不符合所显示的确切模式,即在camelCase中前缀到目标可弃项的字符串“ temp”,则由于无法识别推荐的模式而将产生误报。 通过更名可以轻松消除误报。

  2. 如果目标一次性变量是属性而不是字段或局部属性,则无法识别该模式。 要在这里消除误报,需要编写如下的一次性函数:

     void SomeMethod() { // : HexgridPath = SetGraphicsPath(); // : } GraphicsPath SetGraphicsPath() { GraphicsPath path = null; GraphicsPath tempPath = null; try { tempPath = new GraphicsPath(); tempPath.AddLines(new Point[] { new Point(GridSize.Width*1/3, 0), new Point(GridSize.Width*3/3, 0), new Point(GridSize.Width*4/3,GridSize.Height/2), new Point(GridSize.Width*3/3,GridSize.Height ), new Point(GridSize.Width*1/3,GridSize.Height ), new Point( 0,GridSize.Height/2), new Point(GridSize.Width*1/3, 0) } ); path = tempPath; tempPath = null; } finally { if(tempPath!=null) tempPath.Dispose(); } return path; } 

第一种情况看起来像是一个典型的“初级程序员的首次上课刚出校”错误。

第二种情况可能更难解决,但很烦人。

希望遇到这些误报的其他人可以从此分析中受益。 从长远来看,小的代码更改比简单地禁用错误更好,以防初级程序员下线“优化”补救措施。

我相信删除if (temp != null)将使警告消失。 FxCop不够聪明,无法检查我认为的条件执行路径。

无论如何,我不明白为什么你想出这个代码,而不是简单地使用_bitmapSymbols = new BitmapSymbols(source, sizeSymbols);

暂无
暂无

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

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