Precompile .Net Applications for Better Performance -
Use the NGEN utility to precompile .Net applications to avoid initial start-up and execution lags.

Check us out at

If you're distributing .Net applications to the Desktop, be mindful of first impressions. Typically, WinForms applications present significant start-up and execution lags due to the nature of the CLR JIT compiler. It takes some time to fully convert MISIL (Microsoft Intermediate Language) code to native machine code for execution. While it's doing that, your customer may draw some negative conclusions right off the bat. It can get ugly. To get around this problem, you can use the NGEN utility that ships with the .Net Framework to precompile an .exe file and preload its child assemblies into the GAC. The difference is like night and day.

(Step 1) The default Visual Studio platform target of "Any CPU, Prefer 32-bit" will not work. It may look like NGEN is running, but the native images won't be there. This is the lesson I learned. You will have to change it to "x86 32-bit" which is what you want anyway. WinForms apps run best in this mode. For comparison purposes, trying running your app under "Any CPU" on a 64-bit machine. It will appear really slow.

(Step 2) To see how NGEN works, open the Visual Studio Command Prompt using the "Run as Administrator" command, then type "NGEN install c:\YourExeFile". Next, type "NGEN display c:\YourExeFile" to confirm the native images were created. Now run your app and notice the difference. Wow. It's like a dream come true. It runs like a native complier.

(Step 3) If you're distributing an .exe application in a Visual Studio project, include NGEN.exe as a Resource. Then in your start-up code, copy the file to your main execution directory like so:

// installDir variable holds path where you want to copy ngen file
string path = installDir + ngen.exe;
FileStream fs = null;
using (fs = new FileStream(path, FileMode.Create, FileAccess.Write))
byte[] bytes = null
bytes = Properties.Resources.ngen // pointer to ngen.exe in Resources.resx
fs.Write(bytes, 0, bytes.Length);

(Step 4) After your has installer has run its course, start-up a process and execute NGEN command on your .exe file just before the installer terminates. You will see a command window pop-up echoing back assembly names in the order they are compiled.

Process process1 = new Process
process1.StartInfo.FileName = installDir + "ngen.exe";
process1.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process1.StartInfo.Arguments = " install " + installDir + "YourExeFile.exe";

Hope this helps!

Check us out at