3

我正在编写一些图像处理代码并使用 C# 进行低级像素操作。每隔一段时间,就会发生一次 accessViolationException。

有几种方法可以解决这个典型问题,有些人认为代码应该写得健壮,这样就不会出现访问冲突异常,而且就我而言,应用程序运行良好,但是我想添加一个 try catch 以便如果某些事情是发生这种情况时,应用程序不会以太丑陋的方式失败。

到目前为止,我已经放入了一些示例代码来测试它

unsafe
{
    byte* imageIn = (byte*)img.ImageData.ToPointer();
    int inWidthStep = img.WidthStep;
    int height = img.Height;
    int width = img.Width;
    imageIn[height * inWidthStep + width * 1000] = 100; // make it go wrong
}

当我在这个语句周围放一个 try catch 时,我仍然得到一个异常。有没有办法捕获在不安全块中生成的异常?

编辑:如下所述,除非通过将此属性添加到函数并添加“使用 System.Runtime.ExceptionServices”显式启用对它们的检查,否则不再处理此类异常。

[HandleProcessCorruptedStateExceptions]
    public void makeItCrash(IplImage img)
    {
        try
        {
            unsafe
            {
                byte* imageIn = (byte*)img.ImageData.ToPointer();
                int inWidthStep = img.WidthStep;
                int height = img.Height;
                int width = img.Width;
                imageIn[height * inWidthStep + width * 1000] = 100; // to make it crash
            }
        }
        catch(AccessViolationException e)
        {
            // log the problem and get out
        }
    }
4

1 回答 1

7

ArgumentOutOfRangeException如果参数使您在图像之外写入,请检查大小并返回。

AnAccessViolationException是损坏状态异常 (CSE),而不是结构化异常处理 (SEH) 异常。从 .NET 4 开始,catch(Exception e)除非您使用属性指定它,否则不会捕获 CSE。这是因为您应该首先编写避免 CSE 的代码。您可以在此处阅读有关它的更多信息:http: //msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070035

于 2012-11-07T01:21:41.877 回答