Student222 Student222 - 4 months ago 15
C# Question

(Xamarin, Android) How dose this code help Reduce Referenced Instances?

I am reading the Garbage Collection documentation for Android at Garbage Collection -- Reduce Referenced Instances, I am not quite understand the mechanism of this code

class HiddenReference<T> {

static Dictionary<int, T> table = new Dictionary<int, T> ();
static int idgen = 0;

int id;

public HiddenReference ()
{
lock (table) {
id = idgen ++;
}
}

~HiddenReference ()
{
lock (table) {
table.Remove (id);
}
}

public T Value {
get { lock (table) { return table [id]; } }
set { lock (table) { table [id] = value; } }
}
}

class BetterActivity : Activity {

HiddenReference<List<string>> strings = new HiddenReference<List<string>>();

protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);

strings.Value = new List<string> (
Enumerable.Range (0, 10000)
.Select(v => new string ('x', v % 1000)));
}
}


How does the HiddenReference work? If the GC will recursively scan the instances BetterActivity refers to, can't it see the list in strings field, and then all the strings in the list? I think I am missing something. Any help is appreciated.

Thank you!

Answer

The idea is that HiddenReference has a static Dictionary<T>. Every static object is considered a root object by the garbage collector. This means we have a managed, rooted object. In this case, the GC bridge does not need to check for potential references since it can be sure the object will never be collected.

One note: reducing references from within an Activity is something you should do if you see slowdowns during the GC process. If your app runs fine, don't bother optimizing.