我正在使用 C# & VS2013 和 VSTO。我的代码执行得非常完美,但我遇到的一个问题是,当我转到任务管理器并查看详细信息时,即使之后 Excel 仍然显示为正在运行,我觉得我已经正确清理了。
这是我用来清理和关闭对 Excel 的所有引用的语法。只是对 Excel 和 VSTO 的引用,我省略了腿部工作的肉和肉汁,否则这篇文章会很长。
我有什么设置不正确吗?为什么 Excel 仍然显示在任务管理器中?
namespace ReleaseExcel
{
public partial class Form12 : Form12
{
public static Excel.Worksheet newSeet;
public static Excel._Worksheet currentsheet;
public static Excel._Workbook oWB;
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Workbook activeworkbook;
public Form1()
{
InitializeComponents();
}
private void DoThis()
{
//Showing Declerations to Excel
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Do some more stuff here
//Showing a few more Declerations to Excel
currentsheet = (Excel._Worksheet)(xlWorkBook.ActiveSheet);
Excel.Range last = currentsheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
//Do a bit more stuff
ClearExcel();
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet) != 0) { }
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(currentsheet) != 0) { }
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook) != 0) { }
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) != 0) { }
}
private static void ClearExcel()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
编辑
我添加了GC.Collect()
&GC.WaitForPendingFinalizers()
但现在我的语法挂起
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook) != 0) { }
它已经在这条线上坐了大约 5 分钟,是什么原因导致冻结?
编辑#2
仍然没有这样的运气。这是代码
namespace ReleaseExcel
{
public partial class Form12 : Form12
{
public static Excel.Worksheet newSeet;
public static Excel._Worksheet currentsheet;
public static Excel._Workbook oWB;
public static Excel.Application xlApp;
public static Excel.Workbook xlWorkBook;
public static Excel.Worksheet xlWorkSheet;
public static Excel.Workbook activeworkbook;
public Form1()
{
InitializeComponents();
}
public void btnPush_Click(object sender, EventArgs e)
{
DoThis();
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void DoThis()
{
//Showing Declerations to Excel
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Do some more stuff here
//Showing a few more Declerations to Excel
currentsheet = (Excel._Worksheet)(xlWorkBook.ActiveSheet);
Excel.Range last = currentsheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
}
}
}