Preloading Assemblies

只谈情不闲聊 提交于 2019-12-05 05:22:19

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.

This will however force your users to always take that hit on start up.

In general this is a bad idea (if you have the hit at least defer it till you really need it). A case where it might help is to trigger the load if there is a strong chance that they are going to use the functionality in the near future but the system is otherwise idle. This can be very hard to do accurately though.

You might see whether any of the loaded assemblies are under your control and in the GAC. If so you could ngen them which may have a significant effect on the start up time of this aspect of your UI.

I'm not sure, but I am guessing that not the actual loading of the assemblies is the timeconsuming part - but probably the JIT compiling of the code path. Maybe you want to look at ngen. could be that it makes the performance problem go away. but be sure to understand the implications of that tool.

Links: - http://msdn.microsoft.com/en-us/library/6t9t5wcf.aspx - http://msdn.microsoft.com/en-us/magazine/cc163610.aspx

have a look at the Assembly.Load methods.

Gero

If you are trying to get your assemblies faster, why not have a look at NGEN for your code. Pre JIT everything in the background. This has pro's and con's though depending on what your app is doing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!