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

可能重复:
如何正确清理C#中的Excel互操作对象

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

这个库是从IIS7托pipe的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进程孤立运行在服务器上。

正如有人在评论中提到的,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可以做任何事情…