.netmonogarbage-collectionxamarin.iosboehm-gc

What does it mean if the garbage collector is "more aggressive" in Monotouch 4?


I stumbled about this question: Button in ContentView causes crash in MonoTouch runtime. Bug in Monotouch 4.0? and the inquirer has problems with Monotouch's "more aggressive" garbage collector.

Maybe one of the Xamarin team can sum up some dos and don'ts and give a good explanation?

I am currently upgrading from MT 3.2.6 to MT 4.1 and would like to go through my code and check what has to be changed.


Solution

  • We found that sometimes developers would run into strange problems like dialogs would sometimes stay on the screen, and sometimes they would vanish without leaving a trace and with no explanation of why this happened.

    This typically happened when you created an UIAlertView and kept no references to it, so as far as MonoTouch was concerned, that object was garbage (you did not reference it from your code, so you did not have a use for it).

    But whether the dialog vanished from your screen immediately or later depended on whether the Garbage Collector's heuristics had determined that it was time to run a collection. If you had created a dialog just after a collection, chances are, your dialog would stay on the screen. But if you were very close to a collection, or if you had a background process consuming memory, then the GC would be triggered.

    This in general was confusing to users, "why are things vanishing randomly". The answer was: if you did not keep a reference to it, the GC assumed you did not care.

    To make this more clear to our users, when running MonoTouch on debug mode on the simulator (and there is a command line option to control that for any builds), we added a thread on the simulator that continuously calls GC.Collect() every few seconds. This makes it more obvious that you might have not kept a reference to a dialog of yours.

    Later on, we found out that a very useful and common pattern was to keep two kinds of dialog boxes around that really have no use other than their side effects: UIAlertView and UIActionSheet. We altered MonoTouch so that it internally keeps references to those two until dismissed.

    So we ended up with the best of both worlds: during the development cycle you catch earlier missing references to objects that you need, and we took care of the two most common cases that are only useful for their side effects.