开发者

How are objects generated using reflection garbage collected?

开发者 https://www.devze.com 2022-12-15 13:38 出处:网络
One of my friend told m开发者_如何学编程e that dynamic method is the only way if you want to at run time construct code that can be garbage collected.

One of my friend told m开发者_如何学编程e that dynamic method is the only way if you want to at run time construct code that can be garbage collected.

One question in my mind that how garbage collector garbage the object which generated using reflection?


An object constructed using reflection will be garbage collected like any other type of object, for example when it leaves the scope of a method if it's a method variable.


Garbage collection will collect any .NET objects. It doesn't differ wether they are created using reflection or not.


how should an object created by reflection be different than one created normally?

you have an instance variable of this object... the runtime exactly knows what type of object it is, and also does the GC.

only the way the object is created is different. the object should be exactly the same as one created with new MyObject()


There is more complexity than this. For example, search for Tess (good MS employee) blog about xml serializer leaking memory. There are ways to fix this in code pattern. Anyway, this xml serializer memory leak problem won't be fixed by GC. In fact, these types of dynamically generated dll only get deleted when the parent app is unloaded (IIS worker process that hosts web service that use xml serializer).

Bottom line: even for .Net project, don't rely on GC for all cases. There are leaks that need work-around code/code pattern fix.

This bug is still in 3.5 I think.

More link: http://plainoldstan.blogspot.com/2011/04/wcf-memory-leak-with.html read the Tess link an other link inside this: Are there still known memory leaks with XMLSerialization in .Net 3.5?


Any piece of code that runs under the control of CLR is managed code and CLR governs and decides for garbage collection. there are ways in which you can coltrol the Garbage collection but unless it is really required let CLR decide.

0

精彩评论

暂无评论...
验证码 换一张
取 消