在Excel中正确处理Excel COM对象添加

好吧,我相信这个问题一定要问一百万次,所以对于重复道歉,但我不明白为什么我运行这个应用程序后仍然在我的任务pipe理器中获取COM对象。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Tools.Ribbon; using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; using System.Reflection; using System.Runtime.InteropServices; namespace DataDumpTest { public partial class DataDumpRibbon { private Excel.Application _xlApp = null; private Excel.Workbook _wb = null; private Excel.Worksheet _ws = null; private void DataDumpRibbon_Load(object sender, RibbonUIEventArgs e) { } private void LoadOpenFileDialog() { this.openFileDialog1.Filter = "Excel File (*.XLSX) | *.XLSX"; this.openFileDialog1.Title = "Ariel's Special Definition"; this.openFileDialog1.Multiselect = false; } private void btnDataDump_Click(object sender, RibbonControlEventArgs e) { LoadOpenFileDialog(); if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { _xlApp = new Excel.Application(); _xlApp.Visible = false; _xlApp.DisplayAlerts = false; _xlApp.ScreenUpdating = false; _wb = _xlApp.Workbooks.Open(openFileDialog1.FileName); _ws = _wb.Worksheets["Sheet1"]; _ws.UsedRange.Copy(Type.Missing); // get range to paste into Excel.Worksheet activeWs = Globals.ThisAddIn.Application.ActiveSheet; if (activeWs != null) { Excel.Range rng = activeWs.Cells[1, 1]; rng.Select(); Globals.ThisAddIn.Application.ActiveSheet.Paste(Type.Missing, Type.Missing); } // clean up GC.Collect(); GC.WaitForPendingFinalizers(); Marshal.FinalReleaseComObject(_ws); _wb.Close(Type.Missing, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(_wb); _xlApp.Quit(); Marshal.FinalReleaseComObject(_xlApp); } } } } 

所以我有兴趣处理的COM对象是通过OpenfileDialog1打开的_xlApp,_wb和_ws。 当我debugging这个时,我可以在我的任务pipe理器中看到,当我按下button时,另一个Excel实例显示并不会消失,直到我停止debugging器。 我释放它们的时候不应该消失吗? 我在这里错过了什么?

PS。 这只是一个简单的复制/粘贴从一个Excel到另一个,但我想确保我在这里得到它之前,我继续这个应用程序的其余部分。

嗯,尝试使用:

 Marshal.ReleaseComObject(YourComApp); 

如果仍然不行,在运行Marshal之后尝试将COM对象清零。 我知道在PowerShell中,我也必须转储variables。