C# Proper Way to Close Multiple Excel Objects With Excel Process Destroyed -
I have a C # console program when it runs, it instantates some Excel objects such as: ( OpenXLoos)
When the program is running, I have a way to close Excel (close exxcel) and it is considered to clean Excel process properly. In the Task Manager, I can see the residue of Excel that resides. I was pulled together with examples of Internet shutdown routines:
Private Zero openExcelO (String Dior) {try {xlApp = new} Excel.Application ()} XlWorkBook = xlApp.Workbooks.Open (DIR + "PortfolioApptimization 5.XLSM", 0, False, 5, "", True, Microsoft Office.Error.excel.explatform.exl window, "\ t" , False, false, 0, truth, 1, 0); XL Markowitz = (Excel worksheet) Axel Workbook. Sheet ["Markovitz"]; XlWeights = (Excel Worksheet) xlWorkBook.Sheets ["Weight"]; } Hold (Exception Pre) {ReportError ("Portfolio Optimization", "OpenXcell", ex.ToString ()); }} Private zeros off xx () {object misValue = System.Reflection.Missing.Value; Try {if (xlWeights! = Zero) release object (xlWeights); If (XL Markowitz! = Null) Release Object (XL Markovitz); XlWorkBook Close (wrong, misl, mist value); If (xlApp! = Null) xlApp.Quit (); If (xlWorkBook! = Faucet) Release Object (AxlWorkbook); If (xlap! = Empty) release object (xlap); } Hold (Exceptional Before) {ReportError ("Portfolio Optimization", "Close Xcel", ex.ToString ()); }} Private Zero Release Object (object obj) {try {system.Runtime.InteropServices.Marshal.ReleaseComObject (obj); Obj = null; } Hold (exception pre) {obj = null; Report error ("Portfolio optimization", "Release object", "Unable to release object" + ex.ToString ()); } Finally {GC.Collect (); }} How can I change the shut down routine properly and clean the Excel object so that there is no LINEING excel process in Task Manager?
Thank you!
It seems that you are not releasing your object in the correct order - xlApp Leave out probably can not get out of cleanliness because you are still in the context of the workbook. You need to issue the workbook before leave : < Pre> xlWorkBook.Close (wrong, misswell, misswall); ReleaseObject (xlWorkBook); XlApp.Quit (); ReleaseObject (xlApp); Should go for credit: Other underlying references that you are not closing, i.e., in the following lines:
xlWorkBook = XlApp.Workbooks .Open (...) xlWorkBook.Sheets ["Markowitz"]; The "workbook" object is not being released, nor is the "Sheets" object. You must also release these references, namely:
var books = xlApp.Workbooks; Books.Open (...); ReleaseObject (books); Var sheet = xlWorkBook.Sheets; XL Markowitz = (Excel worksheet) sheet ["Markovitz"]; XlWeights = (Excel Worksheet Sheet ["Weight"]; ReleaseObject (sheet); Great advice from : "Never use two points with COM objects"!
Comments
Post a Comment