Using the new .NET CLR without recompiling
- Posted in:
- .NET
- CodeProject
- General
One of the lesser known capabilities of the new CLR is in-process side-by-side execution. This allows applications that were built on an older version of .NET (before 4.0) to use the new features of the updated CLR without even having to recompile your code!
If assemblies require a specific version of the CLR then the old CLR will load along side the new one to host those assemblies. Keep in mind that, by default, applications built targeting older versions of the .NET framework will continue to run using the corresponding CLR, this is one of the big changes to the CLR preventing existing apps from being forced to use the latest runtime and keeping things backward compatible.
So, let’s say you have an application that was build against .NET 2.0 and you totally want to use the new thread pool features (work stealing, local queues etc.) or even better the new highly optimized background client garbage collector, just add the following to your application configuration file between the configuration element:
<configuration> ... <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> <supportedRuntime version="v2.0.50727" /> </startup> ... </configuration>
Remember that whatever the hosting executable is using as it’s runtime, other assemblies will also be jit’ed using the same CLR. Boom! Your app runs using the latest greatest features and you didn’t even need to compile using .NET. If you don’t believe it, just check the value of System.Environment.Version.
The useLegacyV2RuntimeActivationPolicy attribute is only really necessary if you are loading native assemblies (or mixed mode managed C++ assemblies). You can also specify multiple supported runtimes (in order of support) where the first one found on the system will be used but if the older version is not available on the system your app will happily use CLR4 without moaning about an incompatible framework. A full code example and further reading can be found on the MSDN page.
If you want to force your apps to just use the latest framework that’s available on the machine you can use this relatively undocumented rollForward setting:
<configuration> ... <startup> <process> <rollForward enabled="true" /> </process> </startup> ... </configuration>
This is of course a great thing if you cannot control what version of the .NET framework and application is being built with (like on a build server) but want to get things running on the latest framework. It’s also a low impact way of testing that large applications continue to work when running on the latest CLR without having to build massive solutions. But you should totally start targeting .NET 4.0 to take advantage of the new framework features…