I have written a C# application that makes use of the Visio interop. I'm experiencing an event-related issue that is baffling me. Steps to reproduce:
- Launch Visio
- Launch my application. Visio instance is retrived, the object model can be used, and events are received and handled in my app.
- Close my app- leave Visio open.
- Launch my app. Visio instance is retrieved and the object model can be used, but events are NOT received by my app.
When my app opens, it retrieves an instance to the open Visio App using:
visioApp = (Microsoft.Office.Interop.Visio.Application)Marshal.GetActiveObject("Visio.Application");
I register events like so:
visioApp.DocumentOpened += new EApplication_DocumentOpenedEventHandler(onDocOpened);
When my app shuts down, i unregister the event like so:
visioApp.DocumentOpened -= onDocOpened;
visioApp = null;
It seems like I'm not properly unregistering / letting the instance go when my app shuts down, but thats just a guess. When my app starts the second time, i get no errors- it just doesn't respond to events. I haven't been able to find any further related info online (probably just not searching for the correct terms). Any help is greatly appreciated! I'll provide any more info that might be useful.
@Oscars answer was correct:
Marshal.FinalReleaseComObject(_ap);
However I had one additional problem. Marshal.finalReleaseComObject was being called in a class destructor, which was apparently being called too late in the application shutdown sequence (even if I forced garbage collection), and was not properly releasing the reference. I now call this code earlier (in MainForm_Closing event) and it works well. Thanks for the help!