简体   繁体   中英

C# memory leak using exel and interop COM

UPDATED 3/12/20. I am struggling with a problem where the Excel application is not releasing following my function call below. I'm not sure what references I'm screwing up but I assume I'm somehow leaving a reference to the application because I see multiple Excel processes in my task manager as the program runs, not to mention large amounts of memory use that don't improve with GC. Thoughts?

    static void ParseExcel(string file, SqlConnection conn)
    {
        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file);
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        Excel.Range rng = xlWorksheet.UsedRange;
        SqlCommand cmd = conn.CreateCommand();
        double colCount = rng.Columns.Count;
        double rowCount = rng.Rows.Count;
        //iterate over the rows and columns
        //start on row 2 since row 1 is column headers
        for (int i = 2; i <= rowCount; i++)
        {
            string companyName = "";
            for (int j = 1; j <= colCount; j++)
            {
                //write the value to the console
                if (rng.Cells[i, j] != null && rng.Cells[i, j].Value2 != null)
                {
                    string tst = rng.Cells[i, j].Value2.ToString();
                    switch (j)
                    {
                        case 2:
                            companyName = tst;
                            break;
                    }
                }    //end of column
            }//end of row
            //write to database
            string sql = "insert into dbo.company( ";
            sql += DBI(companyName) + ")";
            Console.WriteLine("sql = " + sql);
            try
            {
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        xlApp.Quit();
        Marshal.ReleaseComObject(rng);
        Marshal.ReleaseComObject(xlWorksheet);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);            
        System.Threading.Thread.Sleep(3000);
    }

and outside call looks like this:

 ParseExcel(@"c:\testfile.xls", conn);
 //cleanup
 GC.Collect();
 GC.WaitForPendingFinalizers();

I should not have made my parse method static. That was the cause of the memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM