I have a WPF application (.NET 4) which has a main window, and inside that main window shows many smaller UserControls
. Various actions performed by the user cause the UserControls
which are displayed to get replaced by different other controls with different data.
I am running into performance problems however, when switching these controls. The WPF dispatcher thread goes to 100% CPU while loading controls. On older machines, or with larger numbers of controls, this can result in the application appearing to lock up for as long as 30 seconds!
Profiling indicates that almost all of this CPU time is spent calling the various InitializeComponent
methods of all the different UserControls
- no one control appears to be vastly worse than any other, they all seem to take between 0.2 and 0.5 seconds (on my dev machine with a fast processor and good graphics card).
As far as I know, InitializeComponent
is where WPF actually loads the compiled xaml into memory.
I'm at a loss for what to do here. I'd like to pre-initialize things on a background thread, but all WPF controls must be created and used on the dispatcher thread, so I don't think this is possible.
Otherwise it looks like the only options I have are to delete all my xaml??
Any help would be greatly appreciated
To revisit this - we do have many complex controls on the screen, but we can't just get rid of them to keep WPF happy!
Further experimentation with profiling showed that using Custom controls (basically just a C# class deriving directly from Control
and defining the UI in a Generic.xaml
themes file only seem to incur the hit of loading and parsing the XAML once. Thereafter, each control just applies the pre-existing theme.
Custom controls are much more difficult to work with than UserControls, but this did seem to help our load performance a lot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With