C # New bitmap () - Out of memory

I am new to DotNet programming. I have a serious problem for me, but I do not know why. I have already used the Dispose() method, but the "out of memory" problem still occurs. For about the first 30 times, everything works fine. Then comes Out of memory . In addition, images range from 13 to 16 MB. This is my code:

 private void advanBtn_Click(object sender, EventArgs e) { InvertFunction(); } private void InverFunction() { Bitmap bm = new Bitmap(imgBox.Image); // Out of memory Image<Gray, byte> EmguImage = new Image<Gray, byte>(bm); EmguImage = EmguImage.Not(); imgBox.Image.Dispose(); imgBox.Image = EmguImage.Bitmap; bm.Dispose(); EmguImage.Dispose(); } 
+5
source share
2 answers

Try the suggestion in the documentation .

The time when the garbage collector decides to destroy the image is not guaranteed. When working with a large image, it is recommended that you call Dispose () to explicitly free the object. Alternatively, use the using keyword in C # to limit the scope of the image.

  using (Bitmap bm = new Bitmap(imgBox.Image)) { using (Image<Gray, Single> image = new Image<Gray, Single>(bm)) { EmguImage = EmguImage.Not(); imgBox.Image.Dispose(); imgBox.Image = EmguImage.Bitmap; } } 

As a last resort, you can try to force garbage collection. BUT this is not recommended and should only be used if you have no other way.

  GC.Collect(); 

I suggest you read about it before using it here .

+2
source

This may not be applicable anymore, but there was some version of the CLR that certainly had errors with LOH, where images are usually distributed. You can check this topic. The workaround was to manually check if there was enough consistent memory (to allocate external memory) before allocating, which is a little painful to do in C #. Just suppose you cannot do something wrong.

I also had problems using OpenCV / Emgu and using opencvsharp for some problems. This is a more direct shell in which you must be very careful in allocating memory. It has been a while, and I cannot remember the exaxt problem. This is due to memory allocation. It should also be fixed, I think.

The presence of both dependencies ends and does not help with clean code.

Otherwise, try using the using statement, which other answers offer. It calls .Dispose () automatically and immediately starts the GC. This way your memory does not fragment. You can also write ..

 using(Image a, Image b, Image c, ...) {} 

... while the object implements IDisposable

+1
source

Source: https://habr.com/ru/post/1270987/


All Articles