但仍無法釋放該元件所使用的記憶體及程序,關閉主程式時會另Excel COM元件成為殭屍並鎖住其表單
正確釋放應該是先使用「Marshal.ReleaseComObject」釋放COM元件,接著在透過GC.Collect及GC.WaitForPendingFinalizers釋放記憶體及程序
程式碼如下:
/// <summary>
/// Close Excel
/// </summary>
private void CloseExcel()
{
if (sheet != null)
{
Marshal.ReleaseComObject(this.sheet);
this.sheet = null;
}
if (workbook != null)
{
//Close workbook
this.workbook.Close(0);
Marshal.ReleaseComObject(this.workbook);
this.workbook = null;
}
if (app != null)
{
//Close app
this.app.Quit();
Marshal.ReleaseComObject(this.app);
this.app = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show("Done","Gererate", MessageBoxButtons.OK);
Process.Start("explorer.exe", CurrentPath);
}