【发布时间】:2009-12-02 18:41:30
【问题描述】:
我在网上阅读了很多关于安全发布 RCW 的文章,在我看来,没有人能就具体需要按什么顺序完成的事情达成一致,所以我想请教各位大佬的意见。例如,可以这样做:
object target = null;
try {
// Instantiate and use the target object.
// Assume we know what we are doing: the contents of this try block
// do in fact represent the entire desired lifetime of the COM object,
// and we are releasing all RCWs in reverse order of acquisition.
} finally {
if(target != null) {
Marshal.FinalReleaseComObject(target);
target = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
然而,有些人主张在Marshal.FinalReleaseComObject 之前进行垃圾收集,有些人在之后,有些人则根本不这样做。真的有必要手动 GC 每一个 RCW,尤其是在它已经从它的 COM 对象中分离之后?
在我看来,将 RCW 从 COM 对象中分离出来并让 RCW 自然过期会更简单、更容易:
object target = null;
try {
// Same content as above.
} finally {
if(target != null) {
Marshal.FinalReleaseComObject(target);
}
}
这样做就足够了吗?
【问题讨论】:
标签: .net com-interop rcw