For some time, I observed an intermittent COM problem in my VSIX package for Visual Studio 2010. Attempting to subscribe to one of the IDE COM-based event streams randomly causes the following error:
"A COM object that has been separated from its base RCW cannot be used
The copy case comes down to this code (which should be used on VSIX, obviously):
using System; using EnvDTE; using EnvDTE80; class Test { private readonly Events _events; private readonly Events2 _events2; private readonly BuildEvents _buildEvents; private readonly ProjectItemsEvents _projectItemsEvents; public Test(IServiceProvider provider) { var dte = (DTE)provider.GetService(typeof(DTE)); var dte2 = (DTE2)dte;
I learned about a possible reason from the numerous descriptions of similar problems that can be found on the network. This is basically a side effect of how Runtime Callable Wrappers and GC interact during COM interactions. Here is a link with a similar problem complete with an explanation.
I am well versed in this explanation, especially because it offers a simple workaround - storing a reference to the event receiver in a field to prevent its premature GC. Indeed, many people seem to have solved the problem this way.
It bothers me that it does not work in my case . I am very surprised why. As you can clearly see, I already kept all references to objects in the fields as a precaution. However, the error is still happening. I tried to be more explicit using GC.KeepAlive() calls at the end of ctor, but to no avail. Is there anything else to do?
Without a solution, my VSIX does not accidentally load, leaving the user with one option: restart Visual Studio and hope that this does not happen next time.
Any help would be really appreciated!
source share