简体   繁体   English

C#Interop执行后不关闭Excel进程

[英]C# Interop not closing Excel process after execution

I have the following blocks of code: 我有以下代码块:

    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(this.pathToFile);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;

I push the xlRange into an array using: 我使用以下命令将xlRange推入数组:

someArray = (System.Object[,])xlRange.Value2;

Afterwards I try to cleanup with: 之后,我尝试使用以下方法进行清理:

    Marshal.ReleaseComObject(xlRange);
    Marshal.ReleaseComObject(xlWorksheet);

    xlWorkbook.Close();
    Marshal.ReleaseComObject(xlWorkbook);
    xlApp.Quit();
    Marshal.ReleaseComObject(xlApp);

However, even with all four of the excel objects being released with Marshal , the process stays open and prevents the file from being opened again. 但是,即使Marshal释放了所有四个excel对象,该过程仍保持打开状态,并阻止了文件再次打开。

Any ideas as to how to properly clean up Interop excel objects? 关于如何正确清理Interop excel对象的任何想法?

I had a similar issue and managed to close the application following this processs; 我遇到了类似的问题,并按照以下过程设法关闭了该应用程序;

GC.Collect();
GC.WaitForPendingFinalizers();

Marshal.FinalReleaseComObject(xlRange);
Marshal.FinalReleaseComObject(xlWorksheet);

xlWorkbook.Close(false, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlWorkbook);

xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM