【发布时间】:2012-03-06 07:05:36
【问题描述】:
每次我运行这段代码时,对象都不会关闭。我仍然在任务管理器中运行了一个 excel.exe。即使我设置了 objects = null,仍然没有。我什至尝试过使用对象 .Quit() 方法。
我在这里做错了什么?
private bool ValidateQM()
{
//setup the objects
Excel.Application oXL = null;
Excel.Workbook oWB = null;
Excel.Worksheet oSheet = null;
int hWnd = 0;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
hWnd = oXL.Application.Hwnd;
oXL.Visible = false;
//Open the workbook.
oWB = oXL.Workbooks.Open(workingForm, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",true, false, 0, true, false, false);
//Get the Worksheet
oSheet = oWB.Worksheets[1];
//Check the date values
string mydatetime = oSheet.Cells[5, 33].Text.ToString() + " " + oSheet.Cells[7, 33].Text.ToString();
string dateofscore = oSheet.Cells[3, 12].Text.ToString();
DateTime.Parse(mydatetime); //make my string a real boy
DateTime.Parse(dateofscore);
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oSheet);
//oWB.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWB);
//oXL.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oXL);
return true;
}
【问题讨论】:
-
代码很糟糕,混合了自动和手动内存管理,最终两者都没有。但它不起作用,因为您正在调试 Debug 构建。 Cells[,] 索引器生成了隐藏的对象引用。当您调试时,它们使 Excel 保持活动状态,直到方法结束。它将在没有调试器的情况下在发布版本中工作。将大部分代码移到单独的方法中以改善结果。
标签: c# object excel-interop