【问题标题】:Many "excel" processes shown on the task manager - processes任务管理器上显示的许多“excel”进程 - 进程
【发布时间】:2011-04-26 17:36:46
【问题描述】:

即使我的应用程序关闭并完成,当我查看任务管理器 -> 进程时,也会出现 有许多 Excel 进程甚至会阻止我的计算机关机。

这是我的代码:

 private void write_data_to_excel(byte[] input)
 {
    FileStream f = File.OpenWrite("StocksData.xls");
    f.Write(input, 0, input.Length);
    f.Close();
 }

导致此问题的另一种可能方法:

private void get_stocks_data()
{
   byte[] result;
   byte[] buffer = new byte[4096];
   try
   {
      WebRequest wr = WebRequest.Create("http://www.tase.co.il/TASE/Pages/ExcelExport.aspx?sn=none&enumTblType=allShares&Columns=noneColumns&Titles=noneTitles&action=1&SubAction=0&GridId=33&CurGuid={0BDA5110-EF93-44CB-A0F0-468C6F502B51}&ExportType=1");
      using (WebResponse response = wr.GetResponse())
      {
         using (Stream responseStream = response.GetResponseStream())
         {
            using (MemoryStream memoryStream = new MemoryStream())
            {
               int count = 0;
               do
               {
                  count = responseStream.Read(buffer, 0, buffer.Length);
                  memoryStream.Write(buffer, 0, count);
               } while (count != 0);
               result = memoryStream.ToArray();
               write_data_to_excel(result);
            }
         }
      }
   }

我的代码还包含:

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(file, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

这些方法被优先调用... 我没有关闭什么或...?

【问题讨论】:

    标签: c# winforms memory-leaks


    【解决方案1】:

    看看How to properly clean up Excel Interop objects in C#。在使用 Excel 互操作时,您需要非常小心地清理所有 COM 对象。帖子中接受的答案将解释为什么您正在做的事情导致该过程保持开放。重点是Never use 2 dots with com objects.

    【讨论】:

      【解决方案2】:

      您需要尝试/捕获打开 Excel 应用程序和任何工作簿的代码,以及关闭打开的工作簿并退出应用程序的 finally 块:

          finally
          {
              if (wb != null) wb.Close();
              if (app != null) app.Quit();
      
              app = null;
          }            
      

      请注意,如果您正在调试代码并在中间停止调试器,您仍将拥有 Excel 进程,因为您的 finally 块将不会执行。

      【讨论】:

        【解决方案3】:

        我发现的最可靠的方法是使用以下方法释放工作簿中的每个工作表:

        System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
        

        然后使用相同的调用释放 Excel 应用程序:

        System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        

        然后去做:

        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        

        【讨论】:

        • 当您将 .NET 引用设置为 null 时,不需要最后两个
        【解决方案4】:

        有时,当 COM 应用程序泄漏时,调用 Marshal.ReleaseComObject() 可以解决问题

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-15
          • 1970-01-01
          • 2017-04-09
          • 2014-03-19
          • 2023-03-12
          • 1970-01-01
          • 2021-11-16
          相关资源
          最近更新 更多