I am having a memory leak problem in this line of code for Computer Vision.
private static void UpdateResultingImage(bool onlyShowFace = false)
{
//memory leaks happen in this method here
if ((imageBitmap == null && faceBitmap == null) || ResultingImage == null)
{
return;
}
if (faceBitmap != null)
{
if (faceBitmapSource == null)
{
faceBitmapSource = Imaging.CreateBitmapSourceFromHBitmap(faceBitmap.GetHbitmap(),
IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
faceBitmapSource = ScaleBitmap(faceBitmapSource, ResultingImage.Width, ResultingImage.Height);
}
else
{
// I think memory leak occurs each time I assign a new BitmapSource before disposing previous bitmap source
//I have tried BitmapSource?.Dispose() to stop memory leak but Dispose() does not exist in BitmapSource class
faceBitmapSource = null;
faceBitmapSource = Imaging.CreateBitmapSourceFromHBitmap(faceBitmap.GetHbitmap(),
IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
faceBitmapSource = ScaleBitmap(faceBitmapSource, ResultingImage.Width, ResultingImage.Height);
}
}
if (imageBitmap != null)
{
if (imageBitmapSource == null)
{
imageBitmapSource = Imaging.CreateBitmapSourceFromHBitmap(imageBitmap.GetHbitmap(),
IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
imageBitmapSource = ScaleBitmap(imageBitmapSource, ResultingImage.Width, ResultingImage.Height);
}
else
{
// I think memory leak occurs each time I assign a new BitmapSource before disposing previous bitmap source
//I have tried BitmapSource?.Dispose() to stop memory leak but Dispose() does not exist in BitmapSource class
imageBitmapSource = null;
imageBitmapSource = Imaging.CreateBitmapSourceFromHBitmap(imageBitmap.GetHbitmap(),
IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
imageBitmapSource = ScaleBitmap(imageBitmapSource, ResultingImage.Width, ResultingImage.Height);
}
}
if (!onlyShowFace)
{
ResultingImage.Source = imageBitmapSource;
return;
}
ResultingImage.Source = faceBitmapSource;
}
I have tried disposing
I have tried using BitmapSource?.Dispose but the Dispose() does not exist in the BitmapSource class. I have also tried setting BitmapSource to null, but to no avail I have tried using GC.Collect() as well, but to no avail. I'm currently out of ideas and will appreciate any help I get