我正在编写一些图像处理代码并使用 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
}
}