22 July 2013

Weak References



I have not personally come across a situation where I've needed to use Weak Reference type in .Net, But while addressing a defect there was a scenario where UI is publishing an event and listen for the responses through event channel frame work built on hardware based java framework. Un fortunately the UI code for publishing the message was written on weak reference type (n later realised this was to address performance related issues)
Occasionally the frameworks that are subscribed to JIT events lose their subscription and stop receiving the events when it is published. The issue was due to the event aggregator that use for JIT publishing uses weak references for the subscribed events which can then be lost when Garbage Collection occurs.
The fix was simple, but to reach in to conclusion it was tough as this was not happening very often. The issue was fixed; basically remove all the weak reference from event aggregator subscription.
A Simple example to test weak reference is given below- 

        static WeakReference _weak;
        public void TriggerWeakRefernce()
        {
            // Assign the WeakReference.
            _weak = new WeakReference(new StringBuilder("eventtChannel"));
            // See if weak reference is alive.
            if (_weak.IsAlive)
            {
                var stringBuilder = _weak.Target as StringBuilder;
                if (stringBuilder != null)
                    Console.WriteLine(stringBuilder.ToString());
            }
            // Invoke GC.Collect.
            // ... If this is commented out, the next condition will evaluate true.
            GC.Collect();

            // Check alive.
            if (_weak.IsAlive)
            {
                Console.WriteLine("Event Channel is Alive");
            }
            // Finish.
            Console.WriteLine("[Done]");
            Console.Read();
        }
 

1 comment:

Anonymous said...

fantabulous article to review i pass on bookmark it too