I'm developing small c# wpf app, using Canon EDSDK libraries. I'm using Live View funcionality, to show live picture from the Canon camera in my desktop application.
During live view process (while loop), application grows in memory. I know it should grow, and after some time GC runs and clears memory. But even after GC clears the memory, it never comes back to the start level.
Also, after a long work my app closes ridiculously long - sometimes it takes even few minutes to close it completely.
I'm expecting, that I have a memory leak, but I can't see where it is.
Here is my live view method with main while loop:
private uint DownloadEvfData(MainWindow MW)
{
uint err = EDSDK.EDS_ERR_OK;
IntPtr stream = new IntPtr();
IntPtr evfImage = new IntPtr();
BitmapImage bmp = new BitmapImage();
var transform = new ScaleTransform(-1, 1, 0, 0);
while (isLVRunning)
{
// Create an Eds Memory Stream
err = EDSDK.EdsCreateMemoryStream(0, out stream);
// Create an Eds EVF Image ref
if (err == EDSDK.EDS_ERR_OK)
{
err = EDSDK.EdsCreateEvfImageRef(stream, out evfImage);
}
// Download the EVF image
if (err == EDSDK.EDS_ERR_OK)
err = EDSDK.EdsDownloadEvfImage(cameraDev,
evfImage);
bmp = GetEvfImage(stream);
// do something with the bitmap
if (bmp != null)
{
// I need to show mirror flipped image
var mirror_bmp = new TransformedBitmap();
mirror_bmp.BeginInit();
mirror_bmp.Source = bmp;
mirror_bmp.Transform = transform;
mirror_bmp.EndInit();
mirror_bmp.Freeze();
MW.image1.Source = null;
MW.image1.Source = mirror_bmp;
RefreshScreen();
bmp = null;
mirror_bmp = null;
}
// Release the Evf Image ref
if (evfImage != null)
{
err = EDSDK.EdsRelease(stream);
evfImage = IntPtr.Zero;
}
// Release the stream
if (stream != null)
{
err = EDSDK.EdsRelease(stream);
stream = IntPtr.Zero;
}
}
transform = null;
return err;
}
And the method that returns single BitmapImage (single frame) for live view looks like this:
public unsafe static BitmapImage GetEvfImage(IntPtr evfStream)
{
IntPtr jpgPointer;
uint err;
uint length = 0;
BitmapImage i = null;
err = EDSDK.EdsGetPointer(evfStream, out jpgPointer);
if (err == EDSDK.EDS_ERR_OK)
err = EDSDK.EdsGetLength(evfStream, out length);
if (err == EDSDK.EDS_ERR_OK)
{
if (length != 0)
{
using (UnmanagedMemoryStream ums = new UnmanagedMemoryStream
((byte*)jpgPointer.ToPointer(), length, length, FileAccess.Read))
{
i = new BitmapImage();
i.BeginInit();
i.CacheOption = BitmapCacheOption.OnLoad;
i.StreamSource = ums;
i.EndInit();
i.Freeze();
}
}
}
return i;
}
What am I doing wrong? Could you please help me trace the leak or show me where is my problem? I was trying to freeze bitmaps before using them as a image source, but the application is still leaking.
I will be very grateful for all your advices.
Thanks
Thanks Dario