Excel crashes on exit


M

Matt Storz

Does anyone know why Excel 2003 crashes on exit after using a .NET
object through COM interop with events? To reproduce the problem, see
the example below...

The C# project and Excel Workbook are available for download at:
http://www.shapescape.com/AClassLibrary.zip

// C# code in Ticker.cs -------------------------------

using System;
using System.Threading;
using System.Runtime.InteropServices;

namespace AClassLibrary
{
public delegate void TickEventHandler();

#region Events raised by COM class
[Guid("B846A796-34E3-4B7E-BDF5-114B875CDCCE")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITickerEvents
{
[DispId(1)] void TickEvent();
}
#endregion

#region Interface published by COM class
[Guid("42EBAA0E-F2F3-499B-9143-6AE919C00F92")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ITicker
{
[DispId(1)] int GetTick();
[DispId(2)] void Dispose();
}
#endregion

[Guid("436E5AB1-ED28-4E4E-B675-98D7473703C7")]
[ProgId("AClassLibrary.Ticker")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(ITickerEvents))]
public class Ticker : ITicker, IDisposable
{
private bool _disposed = false;
private int _tick = 0;
private Timer _timer;
private TimerCallback _timerDelegate;

public event TickEventHandler TickEvent;

public Ticker() : base()
{
_timerDelegate =
new TimerCallback(processTimeEvent);
_timer = new Timer(_timerDelegate, null, 0, 1000);
}

~Ticker()
{
Dispose(false);
}

private void processTimeEvent(Object stateInfo)
{
_tick++;
if (TickEvent != null)
{
TickEvent();
}
}

public int GetTick()
{
return _tick;
}

#region IDisposable Members

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if(!_disposed)
{
if(disposing)
{
_timer.Dispose();
_timer = null;
_timerDelegate = null;
}
}
_disposed = true;
}

#endregion
}
}

‘ VBA code in ThisWorkbook module ------------------------

Private WithEvents ticker As AClassLibrary.Ticker

Private Sub Workbook_Open()
Set ticker = New AClassLibrary.Ticker
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cancel = False Then
ticker.Dispose
Set ticker = Nothing
End If
End Sub

Private Sub ticker_TickEvent()
Dim rng As Range
Set rng = Application.Worksheets("Sheet1").Cells(1, 1)
rng.Value = ticker.GetTick
End Sub
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top