常見.NET功能代碼匯總 (3)
阿新 • • 發佈:2017-06-24
屬於 shee pen a10 使用 con 結束 services service
33,徹底關閉Excel進程
.NET中使用Excel屬於使用非托管資源,使用完成後一般都要用GC回收資源,但是,調用GC的位置不正確,Excel進程可能無法徹底關閉,如下面的代碼:
static void OpenExcelTest(int j) { //Application excel = null; excel = new Application(); excel.Visible = true; excel.Workbooks.Open("d:\\A1000.xla"); Workbook wb = excel.Application.Workbooks.Open("d:\\Book1.xlsx"); Worksheet sh = wb.Worksheets.Item["Sheet1"]; object[,] ssss = sh.Range[sh.Cells[1.1], sh.Cells[3, 1]].Value2; Console.WriteLine("opened excel no. {0}", j); Console.ReadLine();try { //嘗試程序關閉Excel進程 wb.Close(false); sh = null; wb = null; excel.Quit(); } catch (Exception ex) { Console.WriteLine("用戶已經手工結束了Excel進程,內部錯誤消息:{0}",ex.Message ); }int generation = System.GC.GetGeneration(excel); //No.1 //System.Runtime.InteropServices.Marshal.ReleaseComObject(wb); //System.Runtime.InteropServices.Marshal.ReleaseComObject(sh); //System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); excel = null; //No.2 //GC.Collect(generation); Console.WriteLine("close excel no. {0}", j); Console.ReadLine(); }
在上面的代碼中,如果取消 No.1,No.2位置處的註釋,方法結束後,Excel進程是無法結束的,解決辦法,只需要把
GC.Collect();
這行代碼寫到方法之外即可。
Application excel = null;
這個Excel應用程序對象定義在方法內或者外都是可以的,哪怕定義一個靜態變量,結果都沒有影響。
常見.NET功能代碼匯總 (3)