WPF – Dynamic vs Static Resources

memoryperformanceresourceswpf

I am experiencing an enormous memory leak in my WPF project and am trying to figure out what I can do to minimize it. To access resources I use StaticResource 100% of the time. Should I use DynamicResource where I can? Are there advantages as far as memory management between StaticResource and DynamicResource?

FYI: I have a listbox showing data via a DataTemplate. As the user scrolls up/down memory increases fast, reaching 1GB in just a couple of minutes of scrolling up/down.

Best Answer

This is unlikely to be a StaticResource / DynamicResource thing. Static and dynamic refer to lookup strategies, not retention strategies:

  • StaticResource means "look up the resource once, then just keep using the same value."

  • DynamicResource means "look up the resource each time it's needed, in case the value has changed."

What you are doing therefore sounds correct: use StaticResource for unchanging resources such as DataTemplates (and reserve DynamicResource for resources that may change, such as system brushes that might change if the user changes the system colour scheme). The allocation of the DataTemplate via the StaticResource reference will cost no more memory than allocating it via a DynamicResource reference, and long term will be cheaper because WPF doesn't have to keep going back and re-evaluating the reference.

What is more likely is that your template itself is doing something which, when the template is applied (instantiated on a data item), is allocating memory (or indirectly causing memory to be allocated) in a leaky way. One counterintuitive cause that I've seen for this is if the template uses old-style bitmap effects. Another is if the template invokes code-behind that hooks up event handlers. But neither of these is likely to be affected by the way you reference the template resource.