Folks, we had a shocking problem today where C# code was listening for
events from a VB6 component. The COM classes exposed by the VB6 app are
nested and a bit complicated to describe, but a nested class which exposed
events was randomly producing the dreaded "COM object that has been
separated from its underlying RCW cannot be used". The random nature of the
problem hinted that it was garbage or dispose related. After a bit of
suffering I found the following solution (feature and Cursor are COM
classes):

 

GCHandle cursorHandle = GCHandle.Alloc(feature.Cursor, GCHandleType.Normal);

feature.Cursor.NotifyMoveNext += event handler;

feature.ShowModalDialog(...);

if (cursorHandle.IsAllocated)

{

    cursorHandle.Free();

    feature.Cursor.NotifyMoveNext -= event handler;

}

 

It used to randomly die on the removal of the event handler. The Alloc and
Free seem to have totally solved the problem.

 

This code seems a bit obscure and arcane, so I was wondering if anyone had
comments on it. Perhaps there are better ways.

 

Greg

Reply via email to