Question

I have a really big project that I can not easily strip down.

When the application is being closed, I get the error

"InvalidComObjectException: A COM object that has been disconnected from the RCW can not be used."

Details:

System.Runtime.InteropServices.InvalidComObjectException has occured.
  HResult=-2146233049
  Message=A COM object that has been disconnected from its RCW can not be used.
  Source=mscorlib
  StackTrace:
       at System.StubHelpers.StubHelpers.StubRegisterRCW(Object pThis)
  InnerException: 

Unfortunately I can not see what COM object this is about. Does anybody know how I can find that out? Unfortunately I can't read ASM to analyze the disassembly.

Was it helpful?

Solution

There are some steps you could try and since you haven't posted any code I will try to enumerate some of the most common key factors...

First, there is no order when disposing objects. If a close/dispose/finalize action is invoked, object C might be disposed before object A and if some object is still alive it might try to access an already disposed object.

Second, beware of events. It's very common to get errors about accessing a disposed object originated from an event call.

Third, do not dispose objects inside an event scope nor destructors. Create your own method to free your object(s).

Since you don't know which COM object is the culprit, I suggest you look for the ones that you do close, dispose, disconnect, etc...

You might want to read this blog in order to better understand how RCW's work and also to help you with your problem.

Edit:

After reading your comment, I felt I should add two possible causes:

  • If after removing Microsoft.VisualBasic runtime methods you've solved your problem, then I suspect that inside one, or more, of those methods you have incremented the count of a reference to one, or more, of your COM(s) and did not release properly. Be sure to ReleaseComObject checking the reference count until it's 0 and then set it to nothing(VB) or null(C#) and let the Garbage Collector do the rest.

  • The other option is that one of those methods tried to access an already disposed reference to a COM object, resulting in a RCW error, since is no longer callable.

As a final comment, after releasing the COM object always set it to nothing or null, this will release the reference to the variable and you can always check it's availability anywhere in the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top