Search code examples
xamarinmonogarbage-collectionweak-referencescircular-reference

Xamarin garbage collector and circular references


While reading Xamarin docs under section "Performance", I've noticed the following chapter:

The following diagram illustrates a problem that can occur with strong references:

Circular reference

Object A has a strong reference to object B, and object B has a strong reference to object A. Such objects are known as immortal objects due to the presence of the circular strong references. This parent-child relationship is not unusual, and as a result, neither object can be reclaimed by the garbage collector, even if the objects are no longer in use by the application.

That's the first time I've heard of "immortal objects" in C#/.NET/Mono context.

The page then continues with a suggestion to use a WeakReference in one of the objects, which will remove the strong circular reference and fix this "issue".

At the same time, Xamarin docs on garbage collection claim that:

Xamarin.Android uses Mono's Simple Generational garbage collector. This is a mark-and-sweep garbage collector [...]

Aren't mark and sweep GCs unaffected by circular references?


Solution

  • The memory leaks due to circular references apply only for Xamarin.iOS, wich use reference counting for native objects.

    The page about immortal objects also says:

    Boehm – This is a conservative, non-generational garbage collector. It is the default garbage collector used for Xamarin.iOS applications that use the Classic API.

    The second quote specifically talks about Xamarin.Android.