Prevent .Net Memory Leaks with the WeakEventManager

by Ronald 13. Dezember 2009 14:45

When weak events are necessary

A reason for a lot of memory leaks in .Net applications is when event handlers are not deregistered. Basically, there are two kinds of components in an application. The first kind are components that live very long, sometimes as long as your application is running. These components have a "static" or "singleton" character (which doesn't mean that the class must be marked static). Beside these singleton instances, there are usually many instances of classes which do not live for such a long time - let's call them "dynamic" components. Now, what happens when there's a static component which defines an event, and a dynamic component registeres an event handler? This means that the static component references the dynamic component! This fact will prevent the garbage collector from destroying the dynamic component. So what we have to do is to (manually) deregister the event handler at the point when the dynamic component is not needed any more, which might not be easy to determine depending on the design of the system.

The goal of the WeakEventManager

In many of such scenarios, the following behavior would be nice: "If the only references to an instance are references to event handlers, the component should be automatically collected by the GC." We can achieve this by a little helper: The WeakEventManager.

How to use it

The WeakEventManager has methods for adding and removing event handlers as well as for calling the currently registered handlers. For each weak event in a class, you have to instanciate a WeakEventManager which will hold the registered event handlers. Then, you have to overwrite the "add" and "remove" methods of your event and pass the given handler to the WeakEventManager. When you want to raise the event, call the "RaiseEvent" method of the WeakEventManager - that's it!

class StaticComponent
{
	#region MyWeakEvent
	private readonly WeakEventManager _weakEventManager
		= new WeakEventManager();
	
	public event EventHandler MyWeakEvent
	{
		add { _weakEventManager.AddHandler(value); }
		remove { _weakEventManager.RemoveHandler(value); }
	}

	public void OnMyWeakEvent()
	{
		_weakEventManager.RaiseEvent(this, new EventArgs());
	}
	#endregion
}

 


 

VS2008 / Licence: LGPL

WeakEventManager.cs (4,8 kb)

WeakEvents.zip (13,3 kb)

Gib die erste Bewertung ab

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Kommentare

Kommentar schreiben


(Zeigt dein Gravatar icon)  

  Country flag

biuquote
  • Kommentar
  • Live Vorschau
Loading



Powered by BlogEngine.NET 1.4.5.0

RecentPosts

written and designed by TechNewLogic 2010