WeakReference Class

Jul 18, 2009 at 7:26 PM

Hi Josh,

While looking at the code I saw the use of the WeakReference Class. This class references an object even if a garbage collection occurs.

I remember this class being described on Jeffrey Richter's excellent book, CLR via C# 2nd Edition. I will copy paste the lines below because they describe exactly what I want to discuss:

"...if a garbage collection occurred, the objects
that contain the data will be destroyed, and when the program  has to re-create the data, the
program experiences lower performance.
The problem with this technique is the following: Garbage collections do not occur when memory
is full or close to full. Instead, garbage collections occur whenever generation 0 is full, which occurs
approximately after every 256 KB of memory is allocated. So objects are being tossed out of mem-
ory much more frequently than desired, and your application's performance suffers greatly.
Weak references can be used quite effectively in caching scenarios, but building a good cache
algorithm that finds the right balance between memory consumption and speed is very com-
plex."
(from Jeffrey Richter's excellent book, CLR via C# 2nd Edition)

Having followed your articles about WPF and MVVM I decided to search on the internet about WPF and WeakReferences.

I quickly found that WeakReferences are used in WPF's data binding mechanism, under the WeakEvent Pattern umbrella.

My question is:

Is it really a necessary/sufficient condition to use WeakReferences and the WeakEvent Pattern in the MVVM Foundation library? Are the benefits clear?

Maybe some memory profiling and perf should happen in first place? Or if you already done this kind of research, can you post it on your blog, or here, (or why not in your next MSDN article).

 

Best Regards,

Nikos Baxevanis

Coordinator
Jul 19, 2009 at 5:02 AM

Nikos,

I am using WeakReferences because I want to avoid having my classes introduce memory leaks.  Since a Messenger or PropertyObserver object can live for the lifetime of an app, but the object(s) they reference might not, this is an important implementation detail.  In theory I could not use weak references, but that would require the developer to be extremely careful to properly unregister their objects from my types at the right time during an application's life...which isn't always easy to do.  The performance implications of using weak references are neglible, and, compared to the great evil of introducing memory leaks, fully justifiable.  

With that said, if you prefer to not use weak references, you are free to modify my classes as you see fit.

Thanks,

Josh