Marshal.ReleaseComObject(...)问题

时间:2010-06-16 14:22:30

标签: c# excel interop

我在完成后使用所述调用来释放一些Excel对象。之后是否有必要将引用设置为null(如下面的代码所示)?

var dateCol = sheet1.get_Range("C4", "C" + rowOffset);
dateCol.NumberFormat = "Text";
Marshal.ReleaseComObject(dateCol);
dateCol = null;

1 个答案:

答案 0 :(得分:1)

这是我一直使用的,而且效果很好

using Excel = Microsoft.Office.Interop.Excel; 

    Excel.ApplicationClass _Excel; 
    Excel.Workbook WB; 
    Excel.Worksheet WS; 

try 
    { 

    _Excel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    WB = _Excel.Workbooks.Open("FILENAME", 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing); 

        //do something 

    } 
    catch (Exception ex) 
    { 
        WB.Close(false, Type.Missing, Type.Missing); 

        throw; 
    } 
    finally 
    { 
        GC.Collect(); 
        GC.WaitForPendingFinalizers(); 

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(WB); 

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(_Excel); 


    } 

做一个

System.Runtime.InteropServices.Marshal.FinalReleaseComObject

在所有引用的Excel对象上