Has COM object been separated from its RCW?
I'm trying to fix problem with "COM object that has been separated from its underlying RCW cannot be used" error, and I think what's causing it is that COM objects are used on a thread that didn't instantiate them.
I'm not allowed to do much refactoring, and since objects should be available on multiple threads I wonder if there is a way to find out if they have been created on current thread before doing something with them that would cause aforementioned error. And, if they haven't, create them.
Also, I'm new to this interop thing, so if someone would be kind enough to help me understand, I'd much appreciate i开发者_JAVA技巧t:
What happens with the COM object once the thread finishes, and why is RCW still available on the other thread even when it doesn't have the COM object in it anymore (why isn't it null?). Also, why would it cause that error and in the same time return true on Marshal.IsCOMObject?
What happens in the following scenario(s) with reference count and the wrapper and the memory:
- Create COM object x on the thread A
- Pass it and save it on the thread B
- Create another x (alternatively, what would happen if it were y?) on the thread C
- Pass it and overwrite x on the thread B
What happens with the COM object once the thread finishes
The COM object gets destroyed automatically by COM. Which will produce the 'COM object that has been separated' exception message when another thread continues to use it. You cannot allow the thread to exit.
Clearly you have an single threaded COM server, by far the most common kind. It has affinity to the STA thread on which it was created. COM makes sure to automatically marshal any calls made on another thread to the thread that created the object. That can no longer work when the thread is gone. Also beware that you don't get any concurrency.
Another way to get this exception is by making the mistake of handling reference counts explicitly with Marshal.ReleaseComObject(). Not unlikely either since you should have gotten an MDA warning.
精彩评论