The topics described here concentrates fully on pure .Net Framework, describing actual meaning of some programming concepts, FCL and best practices. However you will be using these concepts in all . Net framework compatible languages like Microsoft visual basic .net (VB.Net) or C# .Net (csharp.Net) to build a web application (Asp.Net) or Desktop applications (winforms .net) or Web/Windows services





This blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://Codemine.net
and update your bookmarks.

Monday, October 22, 2007

WeakReference in .Net

There will be scenarios like you have to use a variable or object in .Net, which uses a good part of your computer memory. And then, if the user starts accessing a different part of your application, this object may no longer be necessary and is wasting valuable memory. At this time you can you can end the scope of this variable or delete it, but if the user happens to switch back to this part of the application again, then you'll need to reconstruct this object.

This is the situation in which the WeakReference (System.WeakReference) object in .Net helps us a lot. Also it helps in performance optimization of the application with good memory management.

When the user switches away from the first part of the application, you can create a weak reference to this massive object and destroy all strong references. So that, if memory pressure is high GC will reclaim the memory or else it won’t. You can create a week reference to an object by passing that object as a parameter to the WeakReference’s constructor

Eg:-
WeakReference eg = New WeakReference (obj)

Where obj is your massive object

When the user switches back to the first part of the application, the application can attempt to obtain a strong reference for the massive object (Obj) by accessing the eg’s Target property (WeakReference.Target). If successful, the application doesn't have to do the heavy job of recreating that heavy object again. Target is not a static property so you need to call that object Target property

Eg:-
Obj = eg.Target;

The WeakReference type offers two constructors, this first one receives an object and the second done receives an extra parameter called TrackResurrection which is Boolean value. When this is true, reference is retained after the object's Finalize method has been called. This allows the object to be recreated, but the state of the object remains unpredictable. Use this with heavy objects only and remember that the object WeakReference is also a manage object and will having its own overheads

No comments: