I am having problems getting events to to work right using
COM Interop. I am developing a class library in C# which
is exposed to COM and called by a VBA application. Several
of the classes in the class library raise events and i'm
having no problem recieving these events in my VBA code
(using WithEvents), however as soon as i try to hold more
than one reference to the same object i start getting
crashes when i try and release the references to the
object. It appears that the order that the references are
released is important (This only happens when using
WithEvents). To try and figure out what is going on I have
created a minimal class library and corresponding vba code
which illustrates the problem. (See below)
Explanation:
- NetClass just exposes a single event 'MyEvent' to COM.
(am i doing this wrong?)
- The VBA class defines two variables using WithEvents
which are set to point to the same instance of NetClass
- Trying to set NetObject1 to Nothing without first
setting NetObject2 to Nothing causes a crash. (wtf?)
Please help, this is driving me nuts!
CODE SNIPPET #1 - The .Net class sourcing events:
-----8<----------
using System;
using System.Runtime.InteropServices;
namespace ComInteropEventsTest
{
[ComVisible(false)]
public delegate void MyEventEventHandler();
[Guid("B83B48F0-8F58-4021-AF55-30AC4F72DC6A")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface INetClass_EventSource
{
[DispId(1)] void MyEvent();
}
[Guid("0871D7F5-DFE2-49a0-9FF6-E61C9A1F2187")]
public interface INetClass
{
[DispId(1)] void RaiseEvent();
}
[Guid("B3AD4529-A5EB-4acf-BC33-74E332C50A46")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(INetClass_EventSource))]
public class NetClass: INetClass
{
public event MyEventEventHandler MyEvent;
public void RaiseEvent()
{
if (null!=MyEvent) MyEvent();
}
}
}
-----8<----------
CODE SNIPPET #2 - The VBA class that uses it:
-----8<----------
Option Explicit
Private WithEvents NetObject1 As NetClass
Private WithEvents NetObject2 As NetClass
Public Sub DoStuff()
Set NetObject1 = New NetClass
Set NetObject2 = NetObject1
Set NetObject1 = Nothing ' Crash!
End Sub
-----8<----------
Trevor F. - 15 Apr 2004 07:41 GMT
I just answered my own question (it is a confirmed bug).
For anyone who is interested have a look at Microsoft
Knowledge Base Article - 827418 'BUG: A Visual Basic
Application Stops Responding While It Disconnects from the
Managed Event Source'. There is a fix available from MS.
http://support.microsoft.com/default.aspx?scid=kb;en-
us;827418