Hi Kedar,
This is a case where the lazy garbage collection of .NET becomes observable.
Because you have those event handlers, there are runtime wrappers (RCWs) created for the COM workbook objects.
These wrappers will keep the COM objects alive as long as the wrappers exist.
Since you are not keeping any reference to the wrappers, they will be garbage collected at the next GC run, freeing the COM objects and clearing the entries from the VBA list.
You can explicitly force a garbage collection by calling GC.Collect(). The only trick is to figure out when to call this.
You could add a ribbon button for this, but one option to deal with your specific example is to schedule it to run after the WorkbookDeactivate
private void ApplicationOnWorkbookDeactivate(Workbook wb)
{
ExcelAsyncUtil.QueueAsMacro(() =>
{
GC.Collect();
});
}
That seemed to work for me, but would need some testing and I'd guess you're situation has other places where this issue arises.
Anyway, calling GC.Collect() this way is pretty safe, and will only cause noticeable delay in extreme cases that are not likely to appear in our Excel add-in world.
-Govert