Chapter162:GarbageCollectorin.Net

No Comments

Section162.1:WeakReferences

In .NET, the GC allocates objects when there are no references left to them. Therefore, while an object can still be reachedfromcode(thereisastrongreferencetoit),theGCwillnotallocatethisobject.Thiscanbecomeaproblem if there are a lot of large objects.

Aweakreferenceisareference,thatallowstheGCtocollecttheobjectwhilestillallowingtoaccesstheobject.A weakreferenceisvalidonlyduringtheindeterminateamountoftimeuntiltheobjectiscollectedwhennostrong referencesexist.Whenyouuseaweakreference,theapplicationcanstillobtainastrongreferencetotheobject, whichpreventsitfrombeingcollected.Soweakreferencescanbeusefulforholdingontolargeobjectsthatare expensivetoinitialize,butshouldbeavailableforgarbagecollectioniftheyarenotactivelyinuse.

Simpleusage:

WeakReferencereference=newWeakReference(newobject(),false); GC.Collect();

objecttarget=reference.Target;

if(target!=null)

DoSomething(target);

So weak references could be used to maintain, for example, a cache of objects. However, it is important to remember that there is always the risk that the garbage collector will get to the object before a strong reference is reestablished.

Weakreferencesarealsohandyforavoidingmemoryleaks.Atypicalusecaseiswithevents.

Supposewehavesomehandlertoaneventonasource:

Source.Event+=newEventHandler(Handler)

This code registers an event handler and creates a strong reference from the event source to the listening object. If the source object has a longer lifetime than the listener, and the listener doesn’t need the event anymore when there are no other references to it, using normal .NET events causes a memory leak: the source object holds listener objects in memory that should be garbage collected.

Inthiscase,itmaybeagoodideaistousetheWeakEventPattern.

Somethinglike:

publicstaticclassWeakEventManager

{

publicstaticvoidSetHandler<S,TArgs>(

Action<EventHandler<TArgs>>add,

Action<EventHandler<TArgs>>remove,

Ssubscriber,

Action<S,TArgs>action)

whereTArgs:EventArgs

whereS:class

{

varsubscrWeakRef=newWeakReference(subscriber);

EventHandler<TArgs>handler=null;

handler=(s,e)=>

{

varsubscrStrongRef=subscrWeakRef.TargetasS; if

(subscrStrongRef!=null)

{

action(subscrStrongRef,e);

}

else

{

remove(handler);

handler=null;

}

};

add(handler);

}

}

andusedlikethis:

EventSources=newEventSource();

Subscribersubscriber=newSubscriber();

WeakEventManager.SetHandler<Subscriber,SomeEventArgs>(a=>s.Event+=a,r=>s.Event-=r,

subscriber,(s,e)=>{s.HandleEvent(e); });

Inthiscaseofcoursewehavesomerestrictions-theeventmustbea

publiceventEventHandler<SomeEventArgs>Event;

AsMSDNsuggests:

  • Uselongweakreferencesonlywhennecessaryasthestateoftheobjectisunpredictableafterfinalization. Avoid using weak references to small objects because the pointer itself may be as large or larger.
  • Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application’s objects.

Section162.2:LargeObjectHeapcompaction

BydefaulttheLargeObjectHeapisnotcompactedunliketheclassicObjectHeapwhichcanleadtomemoryfragmentationand further, can lead to OutOfMemoryExceptions

Startingwith.NET4.5.1thereisanoptiontoexplicitlycompacttheLargeObjectHeap(alongwithagarbage collection):

GCSettings.LargeObjectHeapCompactionMode=GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect();

Justasanyexplicitgarbagecollectionrequest(it’scalledrequestbecausetheCLRisnotforcedtoconductit)use with care and by default avoid it if you can since it can de-calibrate GCs statistics, decreasing its performance.

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts

Leave a Comment