On the Startup Performance of a WPF ElementHost in Winforms

By Jay at August 09, 2009 17:34 Tags:

Ce billet est aussi disponible en francais. 

Imagine you're dealing with a relatively complex WinForms application, and you've been so tempted for a while by the charms of WPF that you want to integrate a WPF control somewhere in a form lost in the application. The form in question is opened and closed a lot.

A solution is to develop a WPF control, and integrate it in the WinForms application by using of the ElementHost, this little piece of "magic" that saves a great deal of time.

Soon enough, you'll discover that loading time of the WPF control takes a lot of time... On my machine, a Core 2 Duo 3GHz, that takes something like 3 to 4 seconds before displaying properly the form that contains the ElementHost. And as if it was not enough, the display of the form is done by chunks... Not that fancy... Simple intuition, but that seems to be the loading time of WPF that is too long...

The solution to speed things up is rather simple : Just keep an "empty" ElementHost visible at all times. Place a control of the ElementHost type sized 1x1 somehere on a form that stays visible during the application execution.

The result, a form that shows up in no time and without any visual glitch. Of course, the loading time of the "initial" form that contains the empty ElementHost will still take some time to load, but after that all other forms that contain WPF controls will show up instantly. 

From a more technical point of view, it seems that the initialization of WPF is done when the first ElementHost of the application is initialized, and is released when the last ElementHost of the application is closed. A small analysis using reflector did not show the existence of a method named "InitializeAndKeepWPFInitialized()", and it probably just a matter of instanciating the proper WPF type to intialize WPF... But the empty ElementHost is more than enough !

About me

My name is Jerome Laban, I am a Software Architect, C# MVP and .NET enthustiast from Montréal, QC. You will find my blog on this site, where I'm adding my thoughts on current events, or the things I'm working on, such as the Remote Control for Windows Phone.