【发布时间】:2023-03-21 08:25:02
【问题描述】:
我有一个使用 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 进程。
【问题讨论】:
-
见stackoverflow.com/questions/158706/…Marhsal.ReleaseComObject 是你的朋友。
-
Microsoft 本身建议不要这样做,请参阅此处接受的答案中的讨论和链接:forums.asp.net/t/1804781.aspx/1
-
@Bill 否。我在服务器上安装了 Office,我有一个作为桌面用户帐户运行的应用程序池,并且我的 ASP.NET 项目可以很好地打开文件。问题出在 COM 处理上,与 ASP/IIS 配置关系不大。
标签: c# asp.net excel dispose office-interop