The most efficient way to clear Excel processes in. Net

Source: Internet
Author: User
Tags thread
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 ();
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.