-1

I am using RenderTargetBitmap to render an image which is causing an outofmemory exception. Is there a way to catch that exception so that i can safely exit and tell the user that it was not possible to render the image...instead of crashing the client?

   (MemoryStream imageStream = doSomething())

public Stream doSomething()
{  return renderTarget.Render(); // This is causing the exception  }
user1202434
  • 2,243
  • 4
  • 36
  • 53
  • How large is this image? – Chris Jun 05 '13 at 15:31
  • 1
    @user, that depends. In this situation, you may not have enough memory remaining to tell anything to the user, unless you took steps early on (like reserving some space for this eventuality). The safest move in out-of-memory conditions is usually to let the program scream and die. – Frédéric Hamidi Jun 05 '13 at 15:31
  • What is the source kind of image? if its a Bitmap the target bitmap is simple to big and you Converter ( i guess using the `Image.Save(stream)` method, can not handle that big images. Only solution decrease the size! – Venson Jun 05 '13 at 15:32
  • Did you give `try { ... } catch (OutOfMemoryException ex) { ... }` a go? – user247702 Jun 05 '13 at 15:33
  • 4
    See [When is it OK to catch an OutOfMemoryException and how to handle it?](http://stackoverflow.com/questions/2117142/when-is-it-ok-to-catch-an-outofmemoryexception-and-how-to-handle-it) as it is possible to catch an `OutOfMemoryException`. – XNargaHuntress Jun 05 '13 at 15:34
  • One option may be to use a `MemoryFailPoint` to check if there is enough memory available for your operation. – Mike Zboray Jun 05 '13 at 15:36
  • Can't you know the size of the image before loading it, and check if you have enough memory to load it ? This sounds a bit more gracious for the user. – C4stor Jun 05 '13 at 15:41
  • 1
    @C4stor It's not really that simple. You may have enough memory, but the memory could be too fragmented, for example, if you're loading one large object. – Servy Jun 05 '13 at 15:42
  • thanks @C4stor, that would be ideal...but i dont know how feasible it is... – user1202434 Jun 05 '13 at 15:43
  • The point is the Function to load the image if its once in the memory i know no problem to show it. Mostly the `Image.Save` method is the Problem cause it can not handle big images ... one of the biggest Problems in WPF! – Venson Jun 05 '13 at 15:44
  • @Servy : you're right ! Is it a "common case" you think ? – C4stor Jun 05 '13 at 15:44
  • I updated the question with code – user1202434 Jun 05 '13 at 15:47
  • @C4stor Yes, that's very common. – Servy Jun 05 '13 at 15:48

1 Answers1

0

This is the proper way to do it:

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
}
Yaur
  • 7,333
  • 1
  • 25
  • 36