Melhor maneira de liberar o objeto Excel Interop com
Especialistas, por favor, deixe-me saber a melhor maneira que eu posso fazer isso ...
Eu estou trabalhando em um aplicativo VB.Net que usa o Microsoft.Office.Interop.Excel Object Library para criar planilhas dentro de uma pasta de trabalho e tabelas dinâmicas dentro dessas planilhas.
Meu código é algo como isto:
Dim ExcelApp As New Microsoft.Office.Interop.Excel.Application
Dim wbk As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim wksRawData As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim wksPvtTbl As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim pvtCache As Microsoft.Office.Interop.Excel.PivotCache = Nothing
Dim pvtTables As Microsoft.Office.Interop.Excel.PivotTables = Nothing
Dim pvtTable As Microsoft.Office.Interop.Excel.PivotTable = Nothing
Dim r1 As Microsoft.Office.Interop.Excel.PivotField = Nothing
Dim r2 As Microsoft.Office.Interop.Excel.PivotField = Nothing
Dim df1 As Microsoft.Office.Interop.Excel.PivotField = Nothing
Try
... Create the objects, put in the information
Catch ex As Exception
MessageBox.Show("There was an error creating the Excel file", "Error Creating File", MessageBoxButtons.OK)
Finally
ReleaseObject(r1)
ReleaseObject(r2)
ReleaseObject(df1)
ReleaseObject(pvtTable)
ReleaseObject(pvtTables)
ReleaseObject(pvtCache)
ReleaseObject(wksRawData)
ReleaseObject(wksPvtTbl)
ReleaseObject(wbk)
ExcelApp.DisplayAlerts = True
ExcelApp.Quit()
ReleaseObject(ExcelApp)
ExcelApp = Nothing
wbk = Nothing
wksRawData = Nothing
GC.Collect()
End Try
Então eu tenho código que se parece com o seguinte para meus objetos de lançamento:
Public Sub ReleaseObject(ByRef Reference As Microsoft.Office.Interop.Excel.Application)
Dim i As Integer
If Reference IsNot Nothing Then
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
While i > 0
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
End While
Reference = Nothing
End If
End Sub
Public Sub ReleaseObject(ByRef Reference As Microsoft.Office.Interop.Excel.Workbook)
Dim i As Integer
If Reference IsNot Nothing Then
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
While i > 0
i = System.Runtime.InteropServices.Marshal.ReleaseComObject(Reference)
End While
Reference = Nothing
End If
End Sub
... etc
Eu sei que existem MUITAS soluções lá fora para este tipo de problema, mas eu estou me perdendo em todos os diferentes para saber o que melhor se adapta à minha situação atual ... Isso é uma boa maneira de fazer isso e, se não, o que é maneira mais eficiente?
Obrigado!!!