在一次性物体上配置不正确

时间:2016-08-15 12:06:36

标签: c# idisposable

我有一个函数,它将对象列表绘制到位图上以创建粗略的地图。代码分析会抛出一个警告(CA2000),表示对象'drawPen'未沿所有异常路径放置。据我所知,它被放置在函数的末尾,并且没有无法访问的代码可能会丢失。

有谁知道为什么编译器认为它没有被正确处理?

public void drawUpdates(List<areaObjects> objectLocations)
{
    Rectangle areaToClone = new Rectangle(0, 0, writeOnceMap.Width, writeOnceMap.Height);
    var pixelFormat = writeOnceMap.PixelFormat;
    areaBitMap = writeOnceMap.Clone(areaToClone, pixelFormat);
    Pen drawPen = new Pen(Color.Black, 2);
    drawPen.Width = 2;
    foreach(areaObjectsop2d in objectLocations)
    {
        int xPosition = (int)(op2d.XYZ.xPos * mapScale);
        int yPosition = (int)(op2d.XYZ.yPos * mapScale);
        Point[] crossMarker = getCrossShape(xPosition, yPosition);

        using (var graphics = Graphics.FromImage(areaBitMap))
        {
            graphics.DrawPolygon(drawPen, crossMarker);
        }
    }
    drawPen.Dispose();
}

2 个答案:

答案 0 :(得分:2)

您收到警告,因为在您的函数中发生异常时,drawPen将不会被处理。

您可以在try finally和最终调用.Dispose()或更好的情况下将代码包装起来 - 使用正是这样做的using

public void drawUpdates(List<areaObjects> objectLocations)
{
    Rectangle areaToClone = new Rectangle(0, 0, writeOnceMap.Width, writeOnceMap.Height);
    var pixelFormat = writeOnceMap.PixelFormat;
    areaBitMap = writeOnceMap.Clone(areaToClone, pixelFormat);
    using(Pen drawPen = new Pen(Color.Black, 2))
    {
        foreach(areaObjectsop2d in objectLocations)
        {
            int xPosition = (int)(op2d.XYZ.xPos * mapScale);
            int yPosition = (int)(op2d.XYZ.yPos * mapScale);
            Point[] crossMarker = getCrossShape(xPosition, yPosition);

            using (var graphics = Graphics.FromImage(areaBitMap))
            {
                graphics.DrawPolygon(drawPen, crossMarker);
            }
        }
    }
}

以上相当于:

Pen drawPen = new Pen(Color.Black, 2);
try
{
    /*Your code*/
}
finally
{
    drawPen.Dispose();
}

答案 1 :(得分:2)

想象一下,如果创建笔和处理它之间的代码抛出异常会发生什么。笔不会被丢弃。编译器警告您确保即使发生异常也会处理笔。您有两种方法:usingtry...finally(实际上是using的实现)。

using (Pen drawPen = ...)
{
} // now the code makes sure it gets disposed