The CLR is responsible for many things, such as memory
management, garbage collection, etc. Let us now understand how the CLR engine
takes care of the managed execution of the executables inside of its
environment at runtime.
On compilation of the source in a .NET environment, an
assembly (the MSIL) is generated that houses the IL instructions and metadata.
Now, the Win32 loader loads the CLR and the control is handed over to it. The
CLR, in turn, loads the assembly into its environment and locates the entry
point or the Main. Now, it is the turn of the JIT compiler to optimize (if
optimizations are needed) and translate this MSIL code to the native code to
enable the processor to execute the instructions. As the execution of the code
continues in the context of the CLR, objects are created, used and deleted when
they are no longer needed. These objects are actually created in the managed
heap. Why managed? Because the CLR takes care of when to free these objects and
reclaim the memory to make room for other objects as and when it is needed. The
CLR invokes the garbage collector to reclaim the memory for unused objects in
memory. Learn more on how memory management and garbage collection is handled
by the CLR at the following links.
Garbage Collection in .NET
How to Use Dispose and Finalize in C#