Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Lifetime of types used in generics instantiated using Type.MakeGenericType

$
0
0

Suppose I have a class A<T> {} in my main program, and B is a type that I define at runtime inside a collectible assembly.

Initially, my program obtains the following references:

1) System.Type of B itself (created using Module.DefineType)

2) An instance of an object of type B (created using Activator.CreateInstance)

3) System.Type of A<B> (created using Type.MakeGenericType)

4) An instance of an object of type A<B> (created using Activator.CreateInstance)

It then takes weak references to all 4 of these, sets the original variables to null, and calls GC.Collect and sleeping in a loop until the weak references are all "dropped" (i.e. target becomes null). This is an attempt to wait for all of the actual objects to be reclaimed.

It seems only the instances, (2) and (4) are ever reclaimed. The runtime types B and A<B> are never reclaimed even after there are zero live instances of either type.

If I attempt the same test with only (1) and (2), both the Type B and its instance are reclaimed.

Does it mean that if I ever instantiate a generic class A on a class B then effectively the lifetime of the type B itself becomes as long as A's?

EDIT: This was tested in a debug build. Experimentation shows that the act of taking the 'Target' property and comparing it to null (rather than using the IsAlive property) seems to interfere with reclamation.



Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>