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
、実行した後、まったく実行しないことを推奨する人もいます。特にCOMオブジェクトから既に切り離された後は、すべてのRCWを手動でGCする必要が本当にありますか?
私の考えでは、RCWをCOMオブジェクトから切り離し、RCWを自然に期限切れにする方が簡単で簡単です。
object target = null;
try {
// Same content as above.
} finally {
if(target != null) {
Marshal.FinalReleaseComObject(target);
}
}
それで十分ですか?