可能重复:
如何在 C# 中正确清理 Excel 互操作对象
我有一个使用 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
当我尽最大努力清理尽可能多的对象时,为什么这段代码让孤立的进程在服务器上运行。