C# Weak Event Pattern
Source: http://msdn.microsoft.com/en-us/library/aa970850(v=vs.110).aspx
Who Should Implement the Weak Event Pattern?
Certain scenarios inherently lend themselves to the application of the weak event pattern. One such scenario is data binding. In data binding, it is common for the source object to be completely independent of the listener object, which is a target of a binding. Many aspects of WPF data binding already have the weak event pattern applied in how the events are implemented.
How to Implement the Weak Event Pattern
| Approach | When to Implement | 
|---|---|
| Use an existing weak event manager class | If the event you want to subscribe to has a corresponding WeakEventManager, use the existing weak event manager. For a list of weak event managers that are included with WPF, see the inheritance hierarchy in the WeakEventManager class. Note, however, that there are relatively few weak event managers that are included with WPF, so you will probably need to choose one of the other approaches. | 
| Use a generic weak event manager class | Use a generic WeakEventManager<TEventSource, TEventArgs> when an existing WeakEventManager is not available, you want an easy way to implement, and you are not concerned about efficiency. The generic WeakEventManager<TEventSource, TEventArgs> is less efficient than an existing or custom weak event manager. For example, the generic class does more reflection to discover the event given the event's name. Also, the code to register the event by using the generic WeakEventManager<TEventSource, TEventArgs> is more verbose than using an existing or custom WeakEventManager. | 
| Create a custom weak event manager class | Create a custom WeakEventManager when you an existing WeakEventManager is not available and you want the best efficiency. Using a customWeakEventManager to subscribe to an event will be more efficient, but you do incur the cost of writing more code at the beginning. | 
Sample code for approach 2:
public LeakingWindow() { InitializeComponent(); WeakEventManager<Window, EventArgs> .AddHandler(App.Current.MainWindow, "Activated", MainWindow_Activated); //Traditional event subscription: memory leak ! App.Current.MainWindow.Activated += MainWindow_Activated; } void MainWindow_Activated(object sender, EventArgs e) { //Do something here }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号