Prevent .NET Runtime Optimization Service from running on battery?
The short answer is no, you cant reliably defer ngen (and you shouldnt try), the only consistent/useful option i found was forcing it to run to completion and not leaving it lurk in the background.
If your trying to save some CPU cycles on battery (or in my case stop a server from running ngen after returning it into service following Windows updates) your best option is to force ngen to run yourself. For a desktop PC, 2 options come to mind:
Create a .bat or .ps1 file on your desktop with appropriate ngen command below - just double click and wait for ngen to close before you unplug. If you create the script in your Windows folder instead and shortcut to it on your desktop you can also use Command or Powershell Prompt or the Run dialog to execute it as required (before you unplug/after an update).
Another option that should work is to use a scheduled task to execute the above script. Run it on startup, without a logged on user, as an Administrator. If your laptop is allowed to install updates overnight and can reboot this should work nicely.
To run ngen you only need one of the following commands, use the first/most appropriate option for your system:
.Net 4 or better on 64bit
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe executeQueuedItems
.Net 4 or better on 32bit
C:\Windows\Microsoft.NET\Framework\v4.0.30319\ngen.exe executeQueuedItems
.Net 3 or less on 64bit
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\ngen.exe executeQueuedItems
.Net 3 or less on 32bit
C:\Windows\Microsoft.NET\Framework\v2.0.50727\ngen.exe executeQueuedItems
Below is the minimal output you get from ngen when there are no queued items:
PS C:\Users\Administrator> C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe executeQueuedItems
Microsoft (R) CLR Native Image Generator - Version 4.6.1586.0
Copyright (c) Microsoft Corporation. All rights reserved.
All compilation targets are up to date.
When ngen.exe is ran with executeQueuedItems
it will force it to perform all pending tasks as quickly as possible. Normally ngen runs on a low priority background thread(and apparently just starts at random), the idea being it shouldnt starve other processes of CPU - though that doesnt always work. Running ngen interactively is quicker than leaving it run in the background - but it will impact performance more. How long it takes depends on your hardware and how many/which native images need recompiling.