How to clear COM links in .NET when the application starts?

I am working on a .NET program that launches a new instance of Excel, does some work, and then exits, but must leave Excel. Later, when the program starts again, it will try to connect to the previous instance.

What is the best way to handle the release of COM objects in this situation? If I do not do “ReleaseComObject” in the application object for the first time, then in the second run, get the active object, and then finally free the com object, do I have a memory leak?

The following simplified code illustrates what I'm trying to do:

private Microsoft.Office.Interop.Excel.Application xlsApp;
private Microsoft.Office.Interop.Excel.Workbook xlsWb;

public void RunMeFirst()
{
    //Start a new instance
    System.Type oSEType = Type.GetTypeFromProgID("Excel.Application");
    xlsApp = Activator.CreateInstance(oSEType);
    xlsWb = xlsApp.Workbooks.Open("C:\\test1.xls");

    //Do some stuff

    xlsWb.Close(false);
    Cleanup(ref xlsWb);

    //Do not quit Excel here
    //No Cleanup of xlsApp here?  Is this OK?

    System.Environment.Exit(0);
}

public void RunMeSecond()
{
    //Hook into existing instance
    xlsApp = Marshal.GetActiveObject("Excel.Application");
    xlsWb = xlsApp.Workbooks.Open("C:\\test2.xls");

    //Do some stuff

    xlsWb.Close(false);
    Cleanup(ref xlsWb);

    xlsApp.Quit();
    Cleanup(ref xlsApp);

    System.Environment.Exit(0);
}

public void Cleanup(ref object theObj)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();

    Marshal.FinalReleaseComObject(theObj);
    theObj = null;
}

thank

+3
source share
2 answers

, Office PIA , , , COM. xlsApp xlsWb. , Excel, :

Marshal.FinalReleaseComObject(xlsWb);
xlsWb = null;

Marshal.FinalReleaseComObject(xlsApp);
xlsApp = null;

GC.Collect();

, COM, , , . , !

+4

- RunMeFirst , RunMeSecond ?

, xlsWb :

public void RunMeFirst()
{
    System.Type oSEType = Type.GetTypeFromProgID("Excel.Application");
    xlsApp = Activator.CreateInstance(oSEType);
    Workbook xlsWb = xlsApp.Workbooks.Open("C:\\test1.xls");

    // Do stuff
    xlsWb.Close(false);

    System.Environment.Exit(0);
}

- ReleaseComObject, (, , COM- , ). COM , , COM , GC ( , , 100%).

, xlsWb ( ) , , , . COM, , - null, COM- GC:

xlsWb = null;

GC.Collect - , GC.Collect ReleaseComObject, , , . , , COM-, , .

Marshal.ReleaseComObject Dangerous.

+2

All Articles