tags:

views:

29

answers:

3

Hi there,

I'm not sure if the title is adequate but here is my problem:

I have an app writtten in .NET 4.0 that uses some COM objects. When I set a breakpoint and examine my code too long, when I try to execute a line of code that is related to COM I get an exception. If I step through my code relatively quickly everything is fine.

Is there some switch to prevent this? What is causing this behavior?

The excpetion I get is of type InvalidCastException.

Thanks in advance

A: 

Are these objects remote or local? If remote, perhaps your breakpoints are triggering RPC timeouts.

locka
No, these objects are local.
kamilo
A: 

Are you sure that the reference counting on the COM object(s) is correct. Otherwise, the OS sees that the COM object is not referenced anymore and thus frees it from the memory.

marc ochsenmeier
This is the same code. The difference lies in how fast I step through the code
kamilo
+1  A: 

An InvalidCastException is raised when the IUnknown::QueryInterface() method of the COM interface returns the E_NOINTERFACE error return code. Two basic reasons for that. The usual one is that the COM object simply doesn't implement the interface you are casting to. That's however very repeatable, it cannot be affected by a debugging session.

The second reason is trickier and is related to threading. When you use the RCW in another thread then the CLR will automatically marshal the interface pointer. This requires the COM server to either explicitly implement the IMarshal interface, have a proxy/stub DLL registered (built from the IDL) or to support the standard marshaller (uses the type library).

This is not universally done, there are a lot of COM servers that simply assume they will only be used from a single thread. The debugger comes in to play because of the way it evaluates expressions in the Watch window. It actually runs code to obtain the value of the expression. The exact rules are not well documented that I know of, but sometimes that code will run on a helper thread. Typical for example if you used Debug + Break All to break into the program. That helper thread is going to bomb if the COM server doesn't support marshaling. One thing to check is that the thread that owns the COM object is the current thread. Debug + Windows + Threads and double-click the owning thread (usually the main thread of your app).

Not a great explanation, it is not a slam-dunk for your observation, but I suspect this is close to the problem. Not much you can do about it, avoid using the Watch window to display COM server properties. Or write a bit of debug code to copy the server property into a local variable, put a Watch on that variable instead.

Hans Passant
I dont't have to do anything. No watch window. No evaluations. Just break on breakpoint wait a minute or two and then hit F10 on line with COM object.
kamilo
No idea. At least post some lines of code.
Hans Passant