Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if loading an image will throw an OutOfMemory exception in .NET?

I have an application written using .NET 3.5 SP1 that downloads images from an external site and displays them to end users. On rare ocassions, my users are experiencing OutOfMemory errors because they are downloading enormous images. Sometimes the raw data associated with these images are large, but more often, the dimensions of the images are huge. I realize that I may never be able to get around the fact that these OOM errors are thrown for particular images. It would be VERY helpful, however, if I could somehow determine whether loading a particular image would lead to an OOM issue before I try to load the image.

The data for the images is loaded into a Stream, and then the image itself is turned into a System.Drawing.Image by making a call to System.Drawing.Image.FromStream(stream). I do not have the option of storing these images on disk first. They must be loaded via memory.

If anyone has any tips or suggestions that would allow me to detect that loading an image would lead to an OOM exception, I would very much appreciate it.

like image 630
Keith Avatar asked Jul 07 '10 20:07

Keith


People also ask

How can Outofmemory exception be prevented?

Well, according to the topic of the question, best way to avoid out of memory exception would be not to create objects that fill in that memory. Then you can calculate the length of your queue based on estimate of one object memory capacity. Another way would be to check for memory size in each worker thread.

What causes system OutOfMemoryException?

When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.


1 Answers

You can use MemoryFailPoint class to check for memory availability.

Best

like image 194
Vagaus Avatar answered Sep 23 '22 08:09

Vagaus