What make memory leak in .NET Standard 2.1 bitmap

92 Views Asked by At
     using var stream = new MemoryStream(filteredFrame);
     using var image = Image.FromStream(stream);
     using var resizedBitmap = new Bitmap(image, new Size(640, 320));
     using var resizedImageStream = new MemoryStream();
     resizedBitmap.Save(resizedImageStream, ImageFormat.Jpeg);
     FrameReceived?.Invoke(resizedImageStream.ToArray());

above code is part of method.

printed memory usage, because has guessed to make memory leak in using stream

     using var currentProcess = Process.GetCurrentProcess();
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());
     using var stream = new MemoryStream(filteredFrame);
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());
     using var image = Image.FromStream(stream);
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());
     using var resizedBitmap = new Bitmap(image, new Size(640, 320));
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());
     using var resizedImageStream = new MemoryStream();
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());
     resizedBitmap.Save(resizedImageStream, ImageFormat.Jpeg);
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());
     FrameReceived?.Invoke(resizedImageStream.ToArray());
     Debug.WriteLine(currentProcess.PrivateMemorySize64.ToString());

https://docs.google.com/document/d/1eygcxuGMGveHrHYn59CaPWL69ekKNeWwITUhcGgH1yU/edit?usp=sharing

above link is printing result

Each time the method is called, the memory increases.

I thinks that if use using, the memory should be freed. but memory was just increased

if above code remove, not showing memory leak

Is gc slower than memory allocation speed?

Method is called once every 0.5 seconds.

I used System.Drawing.Common, excution enviorment is arm64 linux .net standard 2.1

Please let me know if I'm using the using syntax incorrectly or if I've made a mistake. Or let me know if you have any other comments about the memory leak.

enter image description here

Above is a visualization of the memory usage log left when my server was forced to reboot twice. The unit is mb.

Garbage collector works, but eventually it builds up too much memory and kills the app.

using MemoryStream stream = new MemoryStream(filteredFrame), resizedImageStream = new MemoryStream();
using Bitmap resizedBitmap = new Bitmap(Image.FromStream(stream), new Size(640, 320));                
resizedBitmap.Save(resizedImageStream, ImageFormat.Jpeg);
FrameReceived?.Invoke(resizedImageStream.ToArray());

Above code is a bit more refactored code.

0

There are 0 best solutions below