3

Possible Duplicate:
Weak references

What is this thing for?

It seems to be a way to create an object that the GC can collect early and if it gets collected early, I am supposed to just re-create it. That sounds to me like caching, but other StackOverflow questions say that this is a lousy cache strategy because the GC in practice will GC your object very eager and fast, (another Q that says weakreference make poor caches) sort of like using ASP.NET's Cache and setting it to a very low cache eviction time limit.

Background: I was recently reading CLR code for TraceSource. In the constructor, the 1st thing that happens is that a WeakReference(this) is added to a static dictionary. Oddly it is only ever used in the Refresh method when TraceSource re-reads the config file for each TraceSource in the dictionary of weak references, but only if it hasn't already been GC'd. And another StackOverflow question indicates this causes memory leaks.

So I've been reading about WeakReferences ever since and getting more and more confused.

Community
  • 1
  • 1
MatthewMartin
  • 32,326
  • 33
  • 105
  • 164

3 Answers3

6

WeakReference is often used for implementing Weak Events. Event handlers are a frequent cause of memory leaks, particularly when you have a long-lived service with events that multiple instances subscribe to. If those instances fail to unregister their event handlers (either because the developer didn't realize it was important or often due to exception cases not triggering the normal cleanup) then the lingering references keep the instances from being collected.

Another good case is if you you want to associate additional data with an existing instance. For instance, you might have an ExtraWidgetInfo that you want to associate with a 3rd-party Widget. One way to create the association is to use a Dictionary. The problem is that now all of the Widgets are kept alive by the Dictionary itself, even if they are no longer used anywhere else. Using a WeakReference for the Widget references keeps the associated data from keeping Widgets alive past their intended expiration.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
3

A cache is a good example. If you use weak references in the cache, items that aren't requested can be garbage collected to reclaim memory.

In short: anything that is handy to retreive, but not critical if you don't.

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
1

Certainly not good for caching because the GC will clean up all currently unreferenced cache-items whenever it runs. It does not wait for memory pressure or something. It does not allow the cache to grow.

usr
  • 168,620
  • 35
  • 240
  • 369