I have read a lot of articles on the net about releasing RCW's safely, and it seems to me that no one can agree on exactly what needs to be done in what order, so I'm asking you guys for your opinions. For example, one could do this:
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();
}
}
However, some people advocate doing the garbage collection before Marshal.FinalReleaseComObject
, some after, and some not at all. Is it really necessary to GC every single RCW manually, especially after it has already been detached from its COM object?
To my mind, it would be simpler and easier to just detach the RCW from the COM object and leave the RCW to expire naturally:
object target = null;
try {
// Same content as above.
} finally {
if(target != null) {
Marshal.FinalReleaseComObject(target);
}
}
Is it sufficient to do that?