Memory leaks once, now, and later will always be a concern in applications. One of its initial origins is the unsubscribed event processing program. Weak event pattern can play a role in Memory leakage, but it has not been implemented yet. In this article, we will see the role of WPF when using the weakeventmanager class.
This article is part of a series of new features of WPF 4.5.
Eneric weak event manager
In previous WPF 4.5, you must create a weak event manger for each event you want to subscribe to. Now you can use a general version of weakeventmanager class.
Dealed event parameters that need to be the source and type of a common parameter type event.
// Type parameters:
// Teventsource:
// The type that raises the event.
//
// Teventargs:
// The type that holds the event data.
Public class weakeventmanager <teventsource, teventargs>:
Weakeventmanager where teventargs: eventargs
It also shows two static variables:
Addhandler adds a handler for a given source event, which uses the event name as the parameter.
Removehandler deletes a handler.
Because reflection is used, there is a small overhead in performance when using this object.
Subscription Interface
In previous WPF 4.5, each weak-event subscription must implement iweakeventlistener, which is very simple:
Public bool receiveweakevent (type managertype, object sender, eventargs E)
Even though it can be implemented easily and quickly, it is indeed quite monotonous. If you want to implement more than what it does not have, you just need to pass a delegate during subscription!
For example:
For example, you have an application with a main window in the program, and sometimes some subwindows are displayed. When an application appears, these subwindows subscribe to activate the main window events. By using the traditional event subscription, you can create a memory leak if you have not registered it. On the other hand, you can use weakeventmanager to subscribe to this event. You have never heard of it!
The following is the sample code:
// Create 10 Mo to be more visible in the process Explorer
Public byte [] DATA = new byte [10*1024*1024];
Public leakingwindow ()
{
Initializecomponent ();
Weakeventmanager <window, eventargs>
. Addhandler (App. Current. mainwindow, "activated", mainwindow_activated );
// Traditional event subhandler: Memory Leak!
App. Current. mainwindow. Activated + = mainwindow_activated;
}
Void mainwindow_activated (Object sender, eventargs E)
{
// Do something here
}