3

I understand the Weak Reference and the Weak Event Pattern.

One place where the weak event pattern is used is in DataBinding between Controls and DataModel. During the process of DataBinding, if the DataModel support INotifyPropertyChange, the Control will ask the DataModel to advise him on change through the event. Without weak event the DataModel would have kept a hard ref on the control. Due to that reference, the control could not be marked as available for GC at the same time as the window become available to be GC.

Microsoft decided to use weak reference to solve this issue.

I wonder if other alternatives like the proposed one would not have been better ?

Alternative: Implement IDisposable on Window with code that pass its children UiElements in order to ask them to remove their DataBinding to the DataModel ? What would have been wrong with that solution ?

Eric Ouellet
  • 10,996
  • 11
  • 84
  • 119
  • What guarantee is there that your window will be closed in any reasonable time, or that you will have a low number of controls that are kept alive after they are unloaded due to a strong reference? There are none, and that's why we have the weak event pattern. –  Aug 30 '12 at 15:37
  • How do you know that Microsoft implements a Weak Event Pattern to accomplish this (i.e. used some sort of WeakEventManager)? – Peter Ritchie Sep 04 '12 at 16:32
  • 1
    Hi Peter, I red it in "WPF Control Development" (excellent book) – Eric Ouellet Sep 05 '12 at 17:04

1 Answers1

5

There's one fundamental advantage in using weak events: the task to unbind the Control from the DataModel is left to the garbage collector itself. The garbage collector typically runs in a low-priority thread that is only activated when the system is idle or when there's need to free up memory, so it doesn't slow down other activities. By contrast, having IDisposable detach the Control from the DataModels means that if you manually dispose of the Control, the unbinding has to take place in the regular caller's thread.

Another aspect (and this is mandated by the MVC pattern) is to leave the model independent from the view. If you think of object lifetime as a dependency, weak references are exactly what it takes to keep the models independent, since you don't have to rely on the controls' cooperation to release the bindings.

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • It sounds logic to me. I wait a week to see if there is a better answer and I will accept your if none. Thanks. – Eric Ouellet Sep 05 '12 at 17:07
  • The interesting question is why there is no weakdelegate? – Pavel Voronin Sep 06 '12 at 19:14
  • @voroninp: a delegate to an instance method must always reference an object, so the reference cannot be weak. On the other hand, a static method delegate never references an object, so it cannot be weak either. You could open a new question about this topic if you like. – GOTO 0 Sep 07 '12 at 15:45