Royi Namir
Royi Namir

Reputation: 148524

C# compile finalize method's on runtime?

As im reading through 3 books about GC , ive notice some strange fact :

C# via CLR

CriticalFinalizerObject : the CLR treats this class and classes derived from it in a very special manner

enter image description here

what ???

"not find enough memory to COMPILE a method? " IMHO - the code should be already compiled... no ?

when Im writing c# code - the whole code is compiled to IL before its running... no? but according to the text - at RUNTIME - he MAY find insufficient memory for compile...

Help ?

Upvotes: 0

Views: 202

Answers (3)

thecoop
thecoop

Reputation: 46098

The JIT compiler only compiles methods from IL to native code at runtime the first time they are executed. As you might expect, this requires extra memory. So, normal finalizers are only compiled right before they are exeucted by the cleanup thread.

An object derived from CriticalFinalizerObject has it's finalizer compiled immediately, so no extra memory is required to execute it at program shutdown. This is for objects that must have their finalizer executed if at all possible (nonwithstanding a power cut or similar)

Upvotes: 5

Alois Kraus
Alois Kraus

Reputation: 13535

With compiler is the JIT compiler meant to compile your finalizer methods eagerly and not to delay its compilation shortly before it is executed.

The deeper reason behind it is that these finalizers are called during application shutdown after all normal finalizers were executed. But the CLR does execute all pending finalizers with a timeout of 2s (at least this was it with .NET 2.0 have not checked since then again). Then the critical finalizers are executed.

Critial finalizer have rare uses e.g. for handles which need to be closed in any case. But you can also use them to hold resources open until all finalizers are executed to enable e.g. tracing even inside finalizers.

Upvotes: 1

llj098
llj098

Reputation: 1412

I think it is the backend of the 'Compiler'. From the IL to the Machine code.

Upvotes: 2

Related Questions