捕获OutOfMemory异常
本文关键字:异常 OutOfMemory 捕获 | 更新日期: 2023-09-27 18:17:09
我正在使用RenderTargetBitmap来渲染导致内存不足异常的图像。是否有一种方法来捕获异常,以便我可以安全退出,并告诉用户,这是不可能渲染图像…而不是使客户端崩溃?
(MemoryStream imageStream = doSomething())
public Stream doSomething()
{ return renderTarget.Render(); // This is causing the exception }
这是正确的做法:
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
}