I am currently working on a .NET 9 WinForms program that contains an ImageViewer, which is a seperate window where you can scroll through a series of images.
My problem is that even after closing the form and taking care of all references to the images which were loaded like this:
ThingFile? imageFile = await ThingData.LoadFileAsync<ThingFile>(Images[Index].ID);
ArgumentNullException.ThrowIfNull(imageFile);
try
{
if (ThingData.VerifyFile(imageFile) && imageFile.Content != null)
{
var imageData = imageFile.Content;
imageFile.Clear();
using var img = new MagickImage(imageData);
if (img.ColorSpace != ColorSpace.sRGB)
{
img.TransformColorSpace(ColorProfile.SRGB);
}
using var ms = new MemoryStream();
img.Write(ms, MagickFormat.Png32);
ms.Position = 0;
using var tempBitmap = new Bitmap(ms);
pictureBox.Image = (Bitmap)tempBitmap.Clone();
imageData = null;
}
else
{
ArgumentNullException.ThrowIfNull(pictureBox.ErrorImage);
pictureBox.Image = (Image)pictureBox.ErrorImage.Clone();
}
}
finally
{
imageFile = null;
}
the allocated RAM is signifficantly bigger than before the whole procedure started. For example, after analysing memory usage with dotMemory, 60MB were used, the ImageViewer got used and closed, and (even after calling the GarbageCollector with GC.Collect(); ) the RAM had gone up to 100MB. The 40MB werent just not freed but lost, since doing the same thing again would end with the RAM being at 140, then 180 and so on...
GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();