根据需要退出excel实例作为类成员

时间:2014-11-04 17:41:25

标签: .net vb.net excel garbage-collection interop

我尝试创建一个我想要使用excel实例的类,我想按需退出该excel实例(如this answer中所述。仍然能够debug it properly我分开了垃圾收集方式如下:

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim xlsInst As New ExcelInst
        GC.Collect()
        GC.WaitForPendingFinalizers()
    End Sub End Class

Public Class ExcelInst
    Sub New()
        Dim myxlApp As New Excel.Application
        Dim myxlWb As Excel.Workbook
        '~~> Add a new Workbook
        myxlWb = myxlApp.Workbooks.Add
        '~~> Display Excel
        myxlApp.Visible = True
        myxlApp.Quit()
    End Sub End Class

一旦加载表单,观察任务管理器excel实例就会正常退出。但我对班级不满意。因为我想拥有myxlAppmyxlWB的私有变量。但如果我把班级改为

Public Class ExcelInst
    Private myxlApp As New Excel.Application
    Private myxlWb As Excel.Workbook

    Sub New()
        '~~> Add a new Workbook
        myxlWb = myxlApp.Workbooks.Add
        '~~> Display Excel
        myxlApp.Visible = True
        myxlApp.Quit()
    End Sub
End Class

excel不再需要关闭了。 Doese有谁知道为什么第一个片段有效(根据我的要求而第二个不是?

1 个答案:

答案 0 :(得分:2)

我认为既然你在GC.Collect之前仍然有对xlsInst的引用,并且该对象包含对excel的引用,那么GC将不会收集。尝试在Collect之前执行xlsInst = Nothing,也可以将类中的变量设置为空。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim xlsInst As New ExcelInst
    xlsInst = Nothing
    GC.Collect()
    GC.WaitForPendingFinalizers()
End Sub End Class

Public Class ExcelInst
    Private myxlApp As New Excel.Application
    Private myxlWb As Excel.Workbook

    Sub New()
        '~~> Add a new Workbook
        myxlWb = myxlApp.Workbooks.Add
        '~~> Display Excel
        myxlApp.Visible = True
        myxlApp.Quit()

        myxlApp = Nothing
        myxlWb = Nothing
    End Sub
End Class

我必须补充一点,我觉得将这个逻辑放在New()中很奇怪。我建议将它放在静态函数中,或者使用.ProcessExcel()或.CloseExcel()函数。