COM object that has been separated from its underlying RCW cannot be used.
-
I am using a third party reference, which is a COM object. The COM object has an Open and Close function and I need to make sure that Close is always called whenever possible. I wrote a wrapper class that implements IDisposable and in the Dispose function, I try to call the Close function. However I get a System.Runtime.InteropServices.InvalidComObjectException when I try to call the close function with additional details of "COM object that has been separated from its underlying RCW cannot be used."
public class MyWrapper : IDisposable
{
private Session _mySession = new Session(); // This is the COM objectpublic void Open() { \_MySession.Open(); } public void Close() { \_MySession.Close(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { \_MySession.Close(); // Calling close without having called open is OK } ~MyWrapper() { Dispose(false); }
}
From my (limited) understanding, there are two reasons why I am getting the exception. 1) The Finalizer is running and calling the destructor, but because the finalizer is on a separate thread I get the error. 2) Based on this Stack Overflow[^] post, the Runtime Callable Wrapper (RCW) has it's own finalizer which is being called before mine, and getting rid of the COM object. I don't know if either of these, or both of these are true, but what is the recommended way to implement a COM object that needs to have finalizer code run?