C# Weak Event Pattern

Source: http://msdn.microsoft.com/en-us/library/aa970850(v=vs.110).aspx

Who Should Implement the Weak Event Pattern?

Implementing the weak event pattern is interesting primarily for control authors. As a control author, you are largely responsible for the behavior and containment of your control and the impact it has on applications in which it is inserted. This includes the control object lifetime behavior, in particular the handling of the described memory leak problem.

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

There are three ways to implement weak event pattern. The following table lists the three approaches and provides some guidance for when you should use each.
 

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
}

 

posted @ 2014-05-13 22:57  t_w  阅读(730)  评论(0)    收藏  举报