Wednesday, October 20, 2010

Memory Leaks in WPF applications

Be aware of the following possible reasons of memory leaks in WPF applications:

Don’t register non-static handlers using EventManager.RegisterClassHandler

for example if you register handler using this code:

image

Declare the handler as static !

image

Otherwise this will cause memory leak.

See also: WPF possible memory leak with EventManager.RegisterClassHandler

Try to avoid PropertyDescriptor.AddValueChanged method to register non-static handlers

image

image

This causes memory leak.

See also: Memory Leaks and Dependency Properties

 

Never use class that is not implementing INotifyPropertyChanged interface as binding source

Never use the simple POCO:

image

as binding source, this causes memory leak,

Instead implement INotifyPropertyChanged:

image

DynamicResource referencing Application level resource

When you use DynamicResource referencing Application level resource in .NET 3.5, use a fix

Yes – this is confirmed bug in .NET framework.

Use Weak Event Pattern when you cannot unsubscribe from event source explicitly

If you subscribe to event on some object – you are creating strong reference to event source object, – this means while target is in memory – source is also in memory.

For example: Suppose if you assign some DataSource of type ObservableCollection to some custom control, and the control subscribes to CollectionChanged event on the DataSource – now if you set another DataSource instance – old instance will be alive until custom control is in memory OR custom control unsubscribes from event (which is not always possible).

See also: WeakEventSource implementation

 

Use WeakReference class when you need to store weak reference to object

The name WeakReference says exactly what the class does – it stores weak reference to the object – this means if there are no strong references to the object from objects in memory, this WeakReference will not hold the target in memory – instead it’s “Taget” name property will return null, and the target itself will be disposed by GC.

 

Be careful when using static variables to store object references

This one is simple – static variable is alive throughout application lifecycle – so if there is any reference stored in static variable – the referenced object is always alive.

I thought I will not make this mistake as it seems as easy to remember – but I had a problem some time ago – I found out that I forgot to clean up value in static variable after objects were not needed anymore.

 

Will write more once I hit any other problems Smile (currently I am intensively testing memory leaks in a large application)

 

Hope this helps,

Kirill

No comments:

Post a Comment