繁体   English   中英

使用exel和interop COM的C#内存泄漏

[英]C# memory leak using exel and interop COM

20 年 3 月 12 日更新。 我正在努力解决以下问题,即 Excel 应用程序未在下面的函数调用后释放。 我不确定我搞砸了哪些引用,但我假设我以某种方式留下了对应用程序的引用,因为我在程序运行时在任务管理器中看到多个 Excel 进程,更不用说大量内存使用了没有用 GC 改进。 想法?

    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);
    }

和外部呼叫看起来像这样:

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

我不应该让我的解析方法是静态的。 这就是内存泄漏的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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