【问题标题】:Unable to diligently close the excel process running in memory无法努力关闭内存中运行的excel进程
【发布时间】:2010-04-21 17:30:18
【问题描述】:

我开发了一个用于从 excel 文件中检索数据的 VB.Net 代码。我以一种形式加载此数据,并在对数据进行必要的修改后将其更新回 excel 中。这个完整的流程运行良好,但大多数时候我观察到即使我关闭了表单;已加载的 excel 进程未正确关闭。

我尝试了所有可能的方法来关闭它,但无法解决问题。找到下面我用于连接到 excel 的代码,如果我可能需要遵循任何其他方法来解决此问题,请告诉我。

注意:我不想杀死 excel 进程,因为它会杀死 excel 的其他实例

将 connectionString 作为字符串调暗

connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; 数据源=" & ExcelFilePath & "; 扩展属性=excel 8.0;持久安全信息=False"

    excelSheetConnection = New ADODB.Connection

    If excelSheetConnection.State = 1 Then excelSheetConnection.Close()
    excelSheetConnection.Open(connectionString)
    objRsExcelSheet = New ADODB.Recordset

    If objRsExcelSheet.State = 1 Then objRsExcelSheet.Close()
    Try
        If TestID = "" Then
            objRsExcelSheet.Open("Select * from [" & ActiveSheet & "$]", excelSheetConnection, 1, 1)
        Else
            objRsExcelSheet.Open("Select Test_ID,Test_Description,Expected_Result,Type,UI_Element,Action,Data,Risk from [" & ActiveSheet & "$] WHERE TEST_Id LIKE '" & TestID & ".%'", excelSheetConnection, 1, 1)
        End If
        getExcelData = objRsExcelSheet
    Catch errObj As System.Runtime.InteropServices.COMException
        MsgBox(errObj.Message, , errObj.Source)
        Return Nothing
    End Try

    excelSheetConnection = Nothing
    objRsExcelSheet = Nothing

【问题讨论】:

    标签: vb.net excel excel-2007 vba


    【解决方案1】:

    您使用的是旧的 VB6 COM 接口。您的代码 sn-p 中没有任何证据表明您曾经在 RecordSet 上调用过 Close()。您无法在 Connection 上调用 Close(),因为您将其设置为 Nothing。

    如前所述,在垃圾收集器运行并且终结器线程释放 COM 接口上的引用计数之前,Excel 不会退出。如果您的程序在处理数据后没有退出或进入休眠状态,这可能需要很长时间。您确实应该考虑提升此代码以使用 System.Data.Oledb 中的类,以便在完成对象后可以正确 Dispose() 一切。

    Q&D解决方案是强制终结器线程运行:

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

    在使用 RecordSet 后运行它。不建议这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2013-04-28
      • 2019-08-29
      • 1970-01-01
      相关资源
      最近更新 更多