tags:

views:

369

answers:

2

Hello. After certain action (pressing a button that starts a sequence of calculations) in the WPF-application a memory leak occurs (it is visible in the task manager in vm size section) approximately on 10 mbytes after each pressing of the button. The sequence of calculations does not contain errors. The use of memory profiler (.NET Memory Profiler) has shown that leaks in .net are not present, but after each pressing of the button the memory size shown in Name/Resource section (marked HeapMemory) increases approximately by 10 mbytes. I've read posts about leaks in WPF but those are not my case definately. What can be wrong? Any suggestions? Maybe, someone had the same problem?

A: 

Perhaps you need to use the WeakEvent Pattern as documented on MSDN to avoid leaks?

Listening for events can lead to memory leaks. The typical technique for listening to an event is to use the language-specific syntax that attaches a handler to an event on a source. For instance, in C#, that syntax is: source.SomeEvent += new SomeEventHandler(MyEventHandler).

This technique creates a strong reference from the event source to the event listener. Ordinarily, attaching an event handler for a listener causes the listener to have an object lifetime that influenced by the object lifetime for the source (unless the event handler is explicitly removed). But in certain circumstances you might want the object lifetime of the listener to be controlled only by other factors, such as whether it currently belongs to the visual tree of the application, and not by the lifetime of the source. Whenever the source object lifetime extends beyond the object lifetime of the listener, the normal event pattern leads to a memory leak: the listener is kept alive longer than intended.

(My emphasis.)

Martin Liversage
+1  A: 

Seeing an increase in the used memory is a misnomer in .NET for detecting a memory leak.

It is easy to make a memory leak in WPF, however. I would suggest using a slightly more visual tool like Redgate Ants Memory Profiler (14 day free trial). Use this method to test for leaks:

  1. Press the button once (to eat up any warmup you might have)
  2. Take a snapshot
  3. Press the button again
  4. Take a snapshot

When you go to the "Class List" and check the filter for "From current snapshot show: only new object". This should give you a better picture of whether you have objects that will never be let go.

The other thing about Ants Memory Profiler is that it has links to videos everywhere that instruct you on how to find a leak. Tracking down leaks is a bit of a black art and it's nice to have help.

No, I don't work for Redgate :)

Anderson Imes