Forum Xamarin.Forms

How to force garbage collection including large memory heap?

JohnHardmanJohnHardman GBUniversity admin

Normally when working in C#, if I want to force a garbage collection, including the large object heap, I would do the following (possibly with extra args on the GC.Collect call):

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
GC.WaitForPendingFinalizers();

Building for mobile using Xamarin.Forms, I don't see the LargeObjectHeapCompactionMode property on GCSettings. Is there an alternative way of forcing everything that is unreferenced to be garbage collected when using XF?

I want to include some code during development that at the press of a button will check that all of my page objects (other than the current page) are no longer referenced. The base class that I use for all page objects keeps track of whether a particular page type has been instantiated but not yet finalized. However, I need to be able to force the finalize of all unreferenced objects when I press the button.

Tagged:

Best Answer

Answers

  • FXamainFXamain Member ✭✭

    Where can we include the garbage collection in the respective platform projects for both Android and ios.

    Is is enough to add it in main.cs in Xamarin.iOS project and onCreate function in mainactivity.cs in Xamarin.Android

  • JohnHardmanJohnHardman GBUniversity admin

    @FXamain said:
    Where can we include the garbage collection in the respective platform projects for both Android and ios.

    Is is enough to add it in main.cs in Xamarin.iOS project and onCreate function in mainactivity.cs in Xamarin.Android

    Five years on, this no longer needs to be in platform-specific code. I now have it in a helper method in portable code.

  • FXamainFXamain Member ✭✭

    Could you please when are moments we have to call Garbage Collection. When logging into to the app is fine Is there any specific information available.

  • JohnHardmanJohnHardman GBUniversity admin

    @FXamain said:
    Could you please when are moments we have to call Garbage Collection. When logging into to the app is fine Is there any specific information available.

    You probably don't need to call Garbage Collection at all. It's done automatically.
    Only do it explicitly if you have a particular need to do so.

  • FXamainFXamain Member ✭✭

    Thanks

Sign In or Register to comment.