Recently, use C # written WinForm, write data in the Excel file to the database, export the data in the DataGrid to Excel format. Finally, Excel memory leaks, there is always an Excel process that cannot be cleared when the application does not quit! I have found a lot of answers online, all useless answers! No matter what the three seven twenty-one kills Excel process, it is not the most effective way! In fact, the most effective way is the following method:
1. Make an Excel operation into a function and call this function. Call gc.collect () in the function, because the GC does not reclaim the code block that calls yourself! 2, call gc.collect (); statement below the function. You will find that the Excel process is not! For example: private void import () {excel.application myexcel = new excel.Application (); myexcel.workbooks.add (openfiledialog1.filename); // ........ // Read the Excel file, import to database // clear garbage excel process myExcel.Workbooks.Close (); myExcel.Quit (); System.Runtime.InteropServices.Marshal.ReleaseComObject (myExcel); myExcel = null;} private void ExcelImport () {Import (); Gc.collect ();} / / The following press button, read the Excel file using the multi-thread, import to the database. 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 ();}}