2

I am getting in out of memory exception while using system.drawing intensively in my windows service.

here is a part of my code:

FileStream fs = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
img = (Image)Image.FromStream(fs).Clone();

The exception is not only raised in this point, it is also raised in other points sometimes where it involves drawing, cropping, resizing, image copy

I am always disposing all the used objects.

I saw this article about the "Out of memory exception" in system.drawing here

and while it is very similar to my case it is different because my testing data is a repeated chain of 40 images, so if there is an issue in one of them it should appear quickly from the first cycle.

I saw the limitation mentioned here

it says that we should not use system.drawing on Win/Web services.

OK, I need to use it with a windows service for massive images processing, what are the alternatives if any?

4

4 回答 4

1

The Image object you are calling Clone on isn't disposed (and maybe there are other similar mistakes in your code). The memory consumed by such objects is only released after the finalizer is run, which needs at least 2 GC cycles and the OutOfMemoryException might very well be thrown on the first GC.
Correctly disposing it should look similar to this:

FileStream fs = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
using(var tmp = Image.FromStream(fs))
  img = (Image)tmp.Clone();
// dispose fs an img after use like usually

Alternatively you could read the entire file into a MemoryStream and pass it to Image.FromStream - this means the image isn't parsed twice which should save additional resources.

于 2010-01-26T14:06:48.170 回答
0

Why are you cloning the image? In your example your are reading the data from the file and then creating a copy. It doesn't take much to throw an out of memory exception in a service with high object throughput.

You could simply do this:

var img = Image.FromFile(ImagePath);
于 2010-01-26T13:34:13.580 回答
0

You're using too much memory too fast, and probably not releasing it as soon as possible.

You need to refactor your code to be more conservative with your resources, and make sure you're not holding onto large objects longer than needed and that you are disposing of your IDisposables at the earliest time.

This process is not easy, nor can it be fully answered in a forum like this.

于 2010-01-26T13:38:01.370 回答
0

这可能无关紧要,但...

我在使用 C++ 中的位图时遇到问题,从较低级别的 Windows API 中获取资源不足错误。这似乎是由于 Windows 内部资源堆在使用 bitblts 等完成绘图时无法处理/分配位图/位图部分造成的。

不知道这样的事情是否会在链条中更进一步地绊倒 dotnet 库。MSDN 上有一个安装设备驱动程序的工具,可用于检查各种桌面堆(不知道这可能与服务有什么关系。)我认为(我使用它已经有一段时间了)它显示了使用的百分比/available - 虽然这可能是一些指标,但我怀疑这些区域的碎片也会导致错误 - 不幸的是我无法完全消除我的问题,但该工具可能会帮助您诊断您的问题。(看起来该工具可能被称为“dheapmon”。)

于 2010-02-01T13:50:09.023 回答