Windows Presentation Foundation provides a very confortable way to
develop rich user experiences. A drop shadow for example can added by
inserting two simple lines of XML. But this simplicity can also mislead
us to overuse them. This leads to performance issues. The following
tipps may help you to avoid or fix them.
- Dispatch expensive calls either within the UI thread with a lower
DispatcherPriority
by callingDispatcher.BeginInvoke()
or to a background thread by using aBackgroundWorker
to keep the UI responsive. - Fix binding errors because they consume a lot of time,
trying to resolve the path error, including searching for attached
properties. You can find them by looking for
System.Windows.Data Error
in the Visual Studio output log. - Reduce the number of visuals by removing unneeded elements, combining layout panels and simplifying templates. This keeps the memory footprint small and improves the rendering performance.
- Prevent Software Rendering. The use of transparent windows by setting
AllowsTransparency
totrue
or using oldBitmapEffects
can cause WPF to render the UI in software on Windows XP, which is much slower. - Load resources when needed. Even thow it's the most comfortable way to merge all resources on application level it can also cost performance by loading all resources at startup. A better approach is to load only often used resources and load the other on view level.
- Virtualize lists and views by using a
VirtualizingStackPanel
asItemsPanel
for lists. This only creates the visible elements at load time. All other elements are lazy created when they get visible. Be aware that grouping orCanContextScrol="True"
prevents virtualization! - Enable Container Recycling. Virtualization brings a lot of
performance improvements, but the containers will be disposed and re
created, this is the default. But you can gain more performance by
recycle containers by setting
VirtualizingStackPanel.VirtualizationMode="Recycling"
- Freeze Freezables by calling
Freeze()
in code orPresentationOptions:Freeze="true"
in XAML. This reduces memory consumption and improves performance, because the system don't need to monitor for changes. - Disable Assembly localization if you don't need it. By using the
[NeutralResourcesLanguageAttribute].
This prevents an expensive lookup for satelite assemblies - Lower the framerate of animations by setting
Storyboard.DesiredFrameRate
to lower the CPU load. The default is 60 frames/second - Use StreamGeometries instead of PathGeometries if possible to draw complex 2D geometries, because they are much more efficient and consume less memory.
Other articles about WPF performance
WPF Performance Tools
There are two interesting tools to trace your WPF application and narrow down performance leaks:- Snoop to check the number of visuals.
- WPF Performance Suite to trace events and rendering time
No comments:
Post a Comment