Trigger Garbage Collection in Xamarin.Forms WPF

CaseCase ✭✭✭USMember ✭✭✭

I have a Xamarin.Forms WPF application in which I take screenshots and write them to an avi file and I am getting Out of Memory issues.
Forms project is netstandard 1.4 and WPF project is NetFramework 4.6.1

The screenshot capture and writing to avi file are all happening in WPF platform code and are being called via dependency service from the forms project. So all the bitmap handling and file writing is occurring in WPF code. The dependency service returns byte[] which are set to null in the forms project once used.

(note, as a UWP app, everything is fine, but var reasons I won't get into, I need a WPF NetFramework project)

The Process Memory tool (in Visual Studio) climbs steadily until it hits about 1.1 Gigs, then crashes.

So to find the issue, I put

Log("Memory => " + GC.GetTotalMemory(false));

throughout the WPF code. At first, I saw the memory climb up to 1.1 Gig just like I see in Visual Studio. After some googling, I found that I had to freeze() all my bitmaps. I did that, and when done with them, I set them to null. Everything that can be wrapped in a using statement is.

Then I put

GC.Collect();
GC.WaitForPendingFinalizers();
Log("Memory => " + GC.GetTotalMemory(true));

throughout the WPF code, and the memory is stabilized (as reported in my logs) but in Visual Studio, I see it keep climbing up to 1.1 Gig then crash!

So how can I be getting to different readings about how much memory is being consumed by that application? And how can I trigger Garbage collection in the forms project since obviously triggering it in WPF isn't doing the job.

Best Answer

  • CaseCase ✭✭✭ US ✭✭✭
    Accepted Answer

    I did that. The issue was the call to Graphics and then calling GetHBitmap which leaves an open handle that you have to dispose of manually. Once I resolved that, no more issues! (the code is posted in a related question on this forum).

Answers

  • LandLuLandLu Xamurai Member, Xamarin Team Xamurai

    Why not store the large file to disk on WPF project, then pass the path to forms. At last you can retrieve this file in the forms through this path.
    It's not a good behavior to keep too much data in memory.

  • CaseCase ✭✭✭ USMember ✭✭✭
    Accepted Answer

    I did that. The issue was the call to Graphics and then calling GetHBitmap which leaves an open handle that you have to dispose of manually. Once I resolved that, no more issues! (the code is posted in a related question on this forum).

Sign In or Register to comment.