捕获OutOfMemory异常

时间:2013-06-05 15:27:14

标签: c# wpf

我正在使用RenderTargetBitmap来渲染导致outofmemory异常的图像。 有没有办法捕获该异常,以便我可以安全地退出并告诉用户不可能渲染图像...而不是崩溃客户端?

   (MemoryStream imageStream = doSomething())

public Stream doSomething()
{  return renderTarget.Render(); // This is causing the exception  }

1 个答案:

答案 0 :(得分:0)

这是正确的方法:

int memEstimateInMB = 16;
try
{
    using(var fp = new MemoryFailPoint(memEstimateInMB))
    {
        return renderTarget.Render();
    }
}
catch(InsufficientMemoryException e) // note that this is a different exception than OOM
{
    // your allocation would have failed (probably)
    // handle accordingy
}