【发布时间】:2022-02-18 10:09:22
【问题描述】:
这是代码,我在其他几个地方看到过用 Marshal.FinalReleaseComObject(...) 关闭对象的实例
每次发送成功消息时都会调用此方法。
public static Excel.Workbook MyBook = null;
public static Excel.Application MyApp = null;
public static Excel.Worksheet MySheet = null;
private static void SuccessLog(string communicationMethod, string portNumber, int messageDelay)
{
Console.WriteLine(Environment.NewLine);
DateTime startTime = DateTime.Now;
string trimDate = Convert.ToString(startTime.ToShortDateString()).Replace('/', '_');
string folder = @"C:\Temp\";
string fileName = Convert.ToString(trimDate);
string message = "Message Sent At: " + Convert.ToString(startTime) + ", via " + communicationMethod + ", at port # " + portNumber + "." + Environment.NewLine;
string fullPath = folder + fileName;
MyApp = new Excel.Application();
MyApp.Visible = false;
var workbooks = MyApp.Workbooks;
if (!File.Exists(fullPath + ".xlsx"))
{
MyBook = workbooks.Add();
MySheet = MyBook.Sheets[1]; // Explicit cast is not required here
int lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
MySheet.Cells[lastRow, 1] = "asdfsa";
MySheet.Cells[lastRow, 2] = "asdfsa";
MySheet.Cells[lastRow, 3] = "asdfsa";
MySheet.Cells[lastRow, 4] = "asdfsa";
MyBook.SaveAs(fullPath);
MyBook.Close(0);
}
else
{
MyBook = workbooks.Open(fullPath + ".xlsx");
MySheet = MyBook.Sheets[1]; // Explicit cast is not required here
int lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
lastRow ++;
MySheet.Cells[lastRow, 1] = "exists?";
MySheet.Cells[lastRow, 2] = "exists?";
MySheet.Cells[lastRow, 3] = "exists?";
MySheet.Cells[lastRow, 4] = "exists?";
MyBook.Save();
MyBook.Close(0);
}
这里是我试图关闭我正在创建的所有对象的地方。我想我可能会遗漏一些对象。
MyApp.Quit();
Marshal.FinalReleaseComObject(MySheet);
Marshal.FinalReleaseComObject(MyBook);
Marshal.FinalReleaseComObject(MyApp);
Marshal.FinalReleaseComObject(workbooks);
Console.WriteLine("Log has been successfully updated or added at: " + fullPath);
Console.WriteLine("Next message will be sent in: " + MessageDelay + " seconds. (Specified in Config.)");
}
【问题讨论】:
-
你在哪里调用代码来释放与上面代码相关的 com 对象?通常,您会将所有代码包装到
try/catch/finally语句中。目前还不清楚最后一个代码 sn-p 被调用的“位置”。 -
抱歉,不清楚这一切都在一个方法中。我还没有把它包装在 try catch 中。在此方法之后,还有另一个方法从调用它的位置运行。
-
是什么让您相信 com 对象没有被释放或 Excel 应用程序没有关闭?在我的小测试中,您的代码似乎成功关闭并释放了它创建的 com 对象。
-
这是个好问题,我可能误解了 com 对象是什么。当我启动和关闭控制台应用程序时,它始终在任务管理器中打开一个。我可以在观看任务管理器时看到它在循环期间创建和关闭 excel 实例,但它在运行时创建的实例并没有关闭。
-
“何时”您“检查” Excel 应用程序是否仍在任务管理器中。在代码退出之前,经理可能不会发布应用程序。换句话说,如果您在代码的最后一行设置断点……
Console.WriteLine("Next message will be sent in: " + MessageDelay + " seconds. (Specified in Config.)");……那么即使代码已发布,Excel 应用程序仍将在任务管理器中可见。当应用程序退出时,Excel 应用程序应该从任务管理器中删除。
标签: c# excel com-interop excel-interop