How dose this code help Reduce Referenced Instances?

JustDoItJustDoIt USMember ✭✭

Hi,

I am reading the Garbage Collection documentation for Android at https://developer.xamarin.com/guides/android/advanced_topics/garbage_collection/

Under section Helping the GC -- 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!

Answers

  • nshpnshp USUniversity ✭✭
    edited February 2017

    Only difference that the dictionary is a managed static field and GC bridge does not need to check for potential references.
    Original answer

Sign In or Register to comment.