Click to See Complete Forum and Search --> : C# Excel Addin – Excel does not unload from memory.


dwventer
June 2nd, 2008, 10:35 AM
Hi,
I’m totally new to C#. I have created a addin with the project wizard in Visual Studio 2008. Everything was going fine until I created a Internet Explorer instance which then uses a event handler (DWebBrowserEvents2_DocumentCompleteEventHandle) to obtain information from the excel application. The code seem to work fine but when I close Excel it goes invisible but I can still see it in my Task Manager.

I suspect it is perhaps a threading issue as I can see that when the event handler fires it does so from a different thread as the main application. Anybody got an idea on how to fix this? I’ll give you some small code snippet from my program.

namespace Myaddin
{
using System;
using Extensibility;
using System.Runtime.InteropServices;
using Office = Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using IE = SHDocVw;
using System.Windows.Forms;

[GuidAttribute("58163470-8309-4716-AED1-B68D70BF193B"), ProgId("easyXL.Connect")]
public class Connect : Object, Extensibility.IDTExtensibility2
{
public void OnConnection(object Application, Extensibility.ext_ConnectMode ConnectMode, object AddInInst, ref System.Array custom)
{
applicationObject = Application;
addInInstance = AddInInst;
if (Application is Excel.Application)
{
excelApp = (Excel.Application)Application;
if (!CommandBarExist())
{
AddMyCommandBar();
}
}
}
private void doExplore(String queryURL,String qPost)
{
object Missing = System.Reflection.Missing.Value;
m_IExplorer = new IE.InternetExplorer();



m_WebBrowser.Visible = true;


IE.DWebBrowserEvents2_DocumentCompleteEventHandler DDocumentCompleteE
= new IE.DWebBrowserEvents2_DocumentCompleteEventHandler(OnDocumentComplete);
m_IExplorer.DocumentComplete += DDocumentCompleteE;
}
void OnDocumentComplete(Object o, ref Object ro)
{
Excel.Worksheet activeSheet = (Excel.Worksheet) excelApp.ActiveSheet;

m_IExplorer.Quit();

}
}

tody4
June 5th, 2008, 10:38 AM
Issue that you are running into is solved simply by decrementing the reference count of the COM object when done with it. The same holds true with any COM Object, it's not released from memory until all references are closed. In this case, Excel is seen as being open and active until you release your reference to it, by calling excelApplication.Quit(). This decrements the "invisible" reference to the application, when you close the "visible" portion that decrements the "visible" reference, therefore freeing both references will result in the object being freed from memory.