为什么我的Excel office对象留下了EXCEL.exe进程?

时间:2012-06-27 13:51:00

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

  

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

我有一个使用Office Interop库进行C#的应用程序。

从使用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进程在服务器上运行。

1 个答案:

答案 0 :(得分:3)

正如评论中提到的那样,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)
        { }

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

编辑:抱歉,没有看到这是一个重复。 Mods可以做任何事......