【问题标题】:Why is my Excel office object leaving behind EXCEL.exe processes? [duplicate]为什么我的 Excel office 对象会留下 EXCEL.exe 进程? [复制]
【发布时间】:2023-03-21 08:25:02
【问题描述】:

可能重复:
How to properly clean up Excel interop objects in C#

我有一个使用 C# 的 Office 互操作库的应用程序。

这个库是从 IIS7 托管的 ASP.NET 应用程序中调用的。

相关代码位为:

/// <summary>
/// Provides excel functions.
/// </summary>
public class ExcelStuff : IDisposable
{
    #region Excel Components

    // The following are pre-allocated Excel objects that must be explicitly disposed of.

    private Excel.Application xApp;
    private Excel.Workbooks xWorkbooks;
    private Excel.Workbook xWorkbook;
    private Excel.Sheets xWorksheets;
    private Excel.Worksheet xWorksheet;
    private Excel.ChartObjects xCharts;
    private Excel.ChartObject xMyChart;
    private Excel.Chart xGraph;
    private Excel.SeriesCollection xSeriesColl;
    private Excel.Series xSeries;

    #endregion

    /// <summary>
    /// Initializes a new instance of the <see cref="ExcelStuff" /> class.
    /// </summary>
    public ExcelStuff()
    {
    }

    /// <summary>
    /// Does some work.
    /// </summary>
    public void DoWork()
    {
        byte[] data = new byte[0];

        worker = new Thread(() =>
        {
            // Do some work.
        });

        worker.Start();
        worker.Join();

        worker.Abort();
        worker = null;

        Dispose();
    }

    /// <summary>
    /// Disposes the current object and cleans up any resources.
    /// </summary>
    public void Dispose()
    {
        // Cleanup
        xWorkbook.Close(false);
        xApp.Quit();

        // Manual disposal because of COM
        xApp = null;
        xWorkbook = null;
        xWorksheets = null;
        xWorksheet = null;
        xCharts = null;
        xMyChart = null;
        xGraph = null;
        xSeriesColl = null;
        xSeries = null;

        GC.Collect();
    }
}

你会注意到代码中有很多冗余,这是我解决这个问题的绝望尝试。 所以请不要告诉我打电话给GC.Collect() 效率低下,或者在班内打电话给Dispose() 不好 - 我已经知道这些事情了。

我想知道的是,当我尽最大努力清理尽可能多的对象时,为什么这段代码会一直在服务器上运行孤立的 EXCEL.exe 进程。

【问题讨论】:

标签: c# asp.net excel dispose office-interop


【解决方案1】:

正如评论中提到的,Marshal.ReleaseComObject 是我用来清理 excel 对象的。这是我的代码示例:

        wb.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

        while (System.Runtime.InteropServices.Marshal.ReleaseComObject(wb) != 0)
        { }

        excelApp.Quit();

        while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp) != 0)
        { }

这似乎对我有用。祝你好运!

编辑:对不起,没看出这是一个骗局。模组可以用这个做任何事情......

【讨论】:

  • 别担心,我还是接受了,这是正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
相关资源
最近更新 更多