使用Type.MakeGenericType实例化的泛型中使用的类型的生命周期 [英] Lifetime of types used in generics instantiated using Type.MakeGenericType

查看:72
本文介绍了使用Type.MakeGenericType实例化的泛型中使用的类型的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有A类A< T>. {}在我的主程序中,而B是我在运行时在可收集程序集中定义的类型.

最初,我的程序获得以下引用:

1)B本身的System.Type(使用Module.DefineType创建)

2)B型对象的实例(使用Activator.CreateInstance创建)

3)A< B>的系统类型. (使用Type.MakeGenericType创建)

4)类型为A< B>的对象的实例. (使用Activator.CreateInstance创建)

然后,对所有这四个参数进行弱引用,将原始变量设置为null,然后调用GC.Collect并在循环中休眠,直到弱引用全部被丢弃"为止. (即目标变为空).这是尝试等待所有 实际要回收的对象.

似乎只回收了实例(2)和(4).运行时类型B和A< B>即使在这两种类型的活动实例为零之后也永远不会被回收.

如果仅用(1)和(2)尝试相同的测试,则类型B及其实例都将被回收.

这是否意味着如果我曾经在类B上实例化一个通用类A,那么类型B本身的生存期就和A一样长了.

这已在调试版本中进行了测试.实验表明,采用"Target"属性并将其与null进行比较(而不是使用IsAlive属性)的行为似乎会干扰回收.

解决方案

您到底想做什么?类型不是GC,实例是GC.加载类型后,除非包含该类型的应用程序域卸载,否则不会将其卸载.

迈克尔·泰勒
http://blogs.msmvps.com/p3net


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.

解决方案

What exactly are you trying to do? Types aren't GC'ed, instances are.  Once a type is loaded it won't be unloaded until the appdomain containing it unloads.

Michael Taylor
http://blogs.msmvps.com/p3net


这篇关于使用Type.MakeGenericType实例化的泛型中使用的类型的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆