The excel| process recently wrote WinForm in C #, writes the data in the Excel file to the database, and exports the data in the DataGrid to Excel format. Finally found Excel memory leak, in the case of the application does not quit, there is always an Excel process can not clear! Find a lot of answers on the internet, are useless answers! What no matter 3,721 kill Excel process, is not the most effective way! In fact, the most effective way is the following:
1. Make a function of Excel operation, then call this function. Calling Gc.collect () in a function is useless because the GC does not reclaim the block of code that calls itself!
2. Call Gc.collect () at the bottom of the function. You will find that the Excel process is gone!
For example:
private void Import () {
Excel.Application myexcel = new Excel.Application ();
MYEXCEL.WORKBOOKS.ADD (Openfiledialog1.filename);
//........
Read the Excel file and import it into the database.
Clear the Excel Garbage process
MyExcel.Workbooks.Close ();
Myexcel.quit ();
System.Runtime.InteropServices.Marshal.ReleaseComObject (Myexcel);
Myexcel = null;
}
private void Excelimport () {
Import ();
Gc. Collect ();
}
Press the Button1 button below to read the Excel file using multithreading and 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 ();
}
}