C# – Preloading Assemblies

.netassembliesc++optimization

At work we use DevExpress for the user interface. The first time a form employing a DevExpress control is opened there's a long pause (sometimes 15-20 sec on some clients). In Visual Studio i can see that tons of assemblies are being loaded during that phase. Is there a way to preload that assemblies into the AppDomain in the background on a thread that is spawned for example before the login screen pops up?

Best Solution

Another choice is to force the JIT to load the assemblies asynchronious instead of doing it by hand. The trick is to simply call the constructor of the control, so the Jit knows that it has to start compiling that particular code path. Usually that forces it to load all dependant assemblies. Just make sure to surround the call of the constructor by a try catch.

An example of how to do that at loadtime:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        PreJitControls();

        Application.Run(new Form1());
    }

    private static void PreJitControls()
    {           
        ThreadPool.QueueUserWorkItem((t) =>
        {
            Thread.Sleep(1000); // Or whatever reasonable amount of time
            try
            {
                AssemblyPullingControl1 c = new AssemblyPullingControl1();
            }
            catch (Exception) { }

            try
            {
                AssemblyPullingControl2 c = new AssemblyPullingControl2();
            }
            catch (Exception) { }

        });
    }
}

But you could also do something similar in the constructor of the login form, if that is a better time to do the pre-loading. Just move the PreJitControls method to the login form and call it from the constructor.