无论我做什么,C#中的Excel互操作都不会实际释放

时间:2016-07-08 21:07:55

标签: c# com-interop excel-interop

我正在使用Excel interop for C#以及完全按照许多不同的地方描述处理它的所有方法,无论我使用哪种方法处理对象,仍然运行Excel.exe进程方法完成后,一切都应该完成并释放。这个过程的存在不会让我感到烦恼,除非你不能在没有先关闭我的应用程序的情况下打开Excel,这恰好会同时终止Excel进程。

如果不想实际确定哪些Excel流程有我的流程的父流程并终止它们,我就不知道还能做什么。

以下是我目前使用的测试方法,无论如何都应该起作用并取决于:

    private bool FillExcelFileWithDataTest()
    {

        string sPath = "C:\\Some.xls";

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range oRange = null;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        var xlWorkbooks = xlApp.Workbooks;
        xlWorkBook = xlWorkbooks.Open(sPath);
        var xlWorksheets = xlWorkBook.Worksheets;
        xlWorkSheet = xlWorksheets.get_Item(1);

        oRange = xlWorkSheet.Cells[1, 1];
        oRange.Value = "Test";

        oRange = xlWorkSheet.Cells[1, 1];
        oRange.Copy();
        oRange = xlWorkSheet.Cells[2, 1];
        oRange.PasteSpecial(Excel.XlPasteType.xlPasteFormats);

        if (oRange != null)
        {
            releaseObject(oRange);
        }

        releaseObject(xlWorkSheet);
        releaseObject(xlWorksheets);
        xlWorkBook.Save();
        xlWorkBook.Close(true, misValue, misValue);
        releaseObject(xlWorkBook);
        releaseObject(xlWorkbooks);
        xlApp.Quit();


        releaseObject(xlWorkSheet);
        releaseObject(xlWorksheets);
        releaseObject(xlWorkBook);
        releaseObject(xlWorkbooks);
        releaseObject(xlApp);

        GC.Collect();
        GC.WaitForPendingFinalizers();

        xlWorkSheet = null;
        xlWorksheets = null;
        xlWorkBook = null;
        xlWorkbooks = null;
        xlApp = null;
        return true;
    }

    private void releaseObject(object obj)
    {
        try
        {
            // Do not catch an exception from this.
            // You may want to remove these guards depending on
            // what you think the semantics should be.
            if (obj != null)
            {
                while(Marshal.FinalReleaseComObject(obj) > 0)
                { }
            }
            // Since passed "by ref" this assingment will be useful
            // (It was not useful in the original, and neither was the
            //  GC.Collect.)
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            //GC.Collect();
        }
    }

我做错了什么?

0 个答案:

没有答案