When I compile an expression into executable code and get the delegate - does the code get garbage collected when no more references to this delegate exist?
Is there any documentation on this? Because I didn't find anything useful in the MSDN.
Yes, the code can be garbage collected. When you call Compile on an Expression of T, the code is compiled into a DynamicMethod, and those are eligible for garbage collection.
Indeed it's not indicated on the MSDN, but you can have a look at the implementation of Expression<T>.Compile in the DLR, which is what .net 4.0 ships:
http://dlr.codeplex.com/SourceControl/changeset/view/54115#990638
Although the implementation of the compiler was different in .net 3.5, DynamicMethods were still used (source: myself, I implemented System.Linq.Expressions in Mono).
The case where compiled expression trees are not collectible, is when you use Expression<T>CompileToMethod, and that you pass a MethodBuilder from an AssemblyBuilder which was not created with the RunAndCollect flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With