【问题标题】:C# memory leak using exel and interop COM使用 exel 和互操作 COM 的 C# 内存泄漏
【发布时间】:2020-06-24 09:03:29
【问题描述】:

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

【问题讨论】:

  • 在告诉编组系统不再需要全部加载的 COM 对象之前,您为什么要尝试进行 GC 清理
  • 好的,我接受了 GC 调用并将它们放在外部调用中的 excel 方法之后。当程序遍历每个单元格时,仍然有大量内存使用。我读了一些关于隐藏范围对象引用的内容?这可能是问题吗?我看到 GC 被反复调用,但没有减少内存/堆。
  • 我正在对堆进行快照,它每隔几秒就会增长 1MB。就像每次它移动到一个新的单元格时,都会发生内存泄漏。我不明白为什么。

标签: c# excel com office-interop com-interop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多