|
最近用C#寫winform,將EXCEL文件中的數據寫入數據庫中,將DataGrid中的數據導出為EXCEL格式。最後發現EXCEL內存洩漏,在應用程序不退出的情況下,總是有一個EXCEL進程不能清除!在網上找了許多答案,都是無用的答案!什麼不管三七二十一殺EXCEL進程啦,不是最有效的方法!其實最有效的方法就是下面這個方法:
1、對excel操作做成一個函數,然後調用此函數。在函數中調用GC.Collect();無用,因為GC不回收調用自己的那一段代碼塊! 2、在函數的下面調用GC.Collect();語句。你會發現EXCEL進程沒有了! 例如: private void Import() { Excel.Application myExcel = new Excel.Application(); myExcel.Workbooks.Add(openFileDialog1.FileName); //........ //讀取EXCEL文件,導入到數據庫. //清除excel垃圾進程 myExcel.Workbooks.Close(); myExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel); myExcel = null; } private void ExcelImport() { Import(); GC.Collect(); } //以下按button1按鈕,使用多線程讀取EXCEL文件,導入到數據庫. private void button1_Click(object sender, System.EventArgs e) { if(openFileDialog1.ShowDialog() == DialogResult.OK) { System.Threading.Thread t=new System.Threading.Thread(new System.Threading.ThreadStart(ExcelImport)); t.Start(); } }
|